Hacker News new | past | comments | ask | show | jobs | submit login
Abusing CSS3's nth-child selector to invent new ones (grack.com)
93 points by mmastrac on Jan 9, 2015 | hide | past | favorite | 43 comments



Be careful with nth-child -- my advice is to only use it with lists where every item is of the same type. It's tempting to start using it with things like tables to style your rows super quickly, but then the second you need to add a single row or column then everything breaks and you need to spend half the day fixing something that should have taken about 5 minutes.


For this reason I am much more a fan of nth-of-type, and all of the -of-type's, since they actually look at the element type and can say, I should style this one but not anything else that may appear at the same level.


I'm really looking forward to CSS selectors level 4. That spec will include a new parameter to nth-child: nth-child(3 [of S]), where S can be any further selector.

http://dev.w3.org/csswg/selectors-4/#child-index


Actually just found out about -of-type's, very powerful.


Since most tables are generated programmatically these days, it's probably easier just to use classes for this kind of styling. And it seems a lot of people forget about the <colgroup> HTML element, which makes it easy to style columns without adding classes to every table cell.


It's probably even easier to just put inline styles on every row, but neither of those practices are going to result in maintainable markup.

By adding classes for the singular purpose of styling them, you tie your markup to the appearance of the web page. Instead, classes should be used to further describe the contents of elements in relation to each other. Then all the presentational rules can be kept in CSS, and selectors can be used to style based on the meaning of the content.

This means the style of the page can change without modifying the markup. And if the styles are written well enough, they can be applied to any (sane) markup.

Oh and +1 for colgroup!


I agree that classes are the best bet. In terms of colgroup, the one issue is that it won't work if you're using colspan on only a subset of your rows.


Nicely done -- this reminds me of a technique outlined by Andre Luis and Lea Verou here: http://lea.verou.me/2011/01/styling-children-based-on-their-...

Building on these selectors and giving them meaningful names is a nice way of taking it a step further.


Lea Verou's article is from 2011 and this article is basically a repost from 2015.


High level question: Why do we need to care about such things? Or, what's wrong with just HTML and just some simple usage of old CSS3 or whatever it was? That is, why do Web pages need to be so complicated? Since we have decades of word whacking software without such features, why do we need such features now?

My Web pages are all really simple: Each is 800 pixels wide, with just a little use of CSS and then nearly all just HTML, with the layout using tables. I have yet to write a single line of JavaScript although Microsoft's ASP.NET writes a little for me.

To me, my Web pages look quite functional, usable, easy to understand and use, etc.

For the need for a lot more, I don't get it and worse: On the Internet I see a lot of really complicated Web pages that jump around while loading and then again when I use my mouse to put the page into the focus and use the scroll wheel on the mouse to scroll the page. I don't like the jumping around.

Why go to the trouble to build such complicated Web pages?

I'm not criticizing but trying to learn and inviting answers.

Why bother? HTML was just another text markup language, and nice, and CSS helped a little. Isn't that enough?

I learned some HTML, and it was fine, and now I want to move on and just use it and not stop here and make a career out of adding unbounded complexity.

Shouldn't things be as simple as possible but not simpler? Why be so complicated? To me, the complicated Web pages I see are a disaster, slow down my computer, etc. -- I'd much rather have just simple Web pages with old HTML, only simple CSS, and little or no JavaScript.


Sorry, can't and won't get onboard with this. It's not 1995 anymore. Join the rest of us in the 21st century with pages that are functional and attractive.


and maintainable.


It sounds like you have in mind a set of likely changes and have designed the HTML, CSS, and JavaScript to make the changes in that set relatively easy. Okay. For my Web pages, I questioned if that candle was worth a match. Or another such analogy goes, "Don't build a brick outhouse.". Or as I wrote, as simple as possible but not simpler. It's just a Web page! But that's the way I've been thinking and posted here to see where people differ in their thinking.

One possible issue is changing where the text, pictures, video clips, ads, etc. are depending on the number of pixels or whatever in the user's screen, browser window, etc. For my pages, I just decided not to do that -- I just didn't see any very big reason to do that. Or, if a user gets used to my Web pages, then they will still have the same layout -- text, text boxes, URLs, ads, links to Help, etc. on any other screen, with any other browser, etc.

Is it really important to change what the page looks like depending on the user's screen size? Or, if we know what text, ads, text boxes, etc. we want, can't we just display it, basically one way for everyone? Why so important to change? As a programmer it's more work for me, and as a user I just want it simple.


Because going to all this trouble has distinct advantages.

- With media queries in CSS my page can be responsive, scaling its size and content from 320px smartphones to multi-monitor desktops. I don't have to build and maintain multiple pages or specifically target individual devices. - Using semantic tags makes it simpler for search engines to index your content and for visually impaired people to use screen readers and understand it. - With advanced JavaScript I can reduce the friction of multi-page forms. AJAX lets us do instant checks on data against a remote database without loading the rest of the layout. Google helpfully suggests the rest of your query as you type.

Of course, it's not hard to go overboard with modern web tech, and these features can introduce bugs and alienate users running old hardware and software. But such is the price of progress.


> - With media queries in CSS my page can be responsive, scaling its size and content from 320px smartphones to multi-monitor desktops.

I guess I just don't want my pages to change, just want them to look the same. On a big screen on a desktop computer, one of my pages is still just 800 pixels wide -- that's all I need for what I'm trying to display to the user. I'm not trying to take up his whole screen.

I see what from the user side Google has done with AJAX -- it's nice. But Google has nearly infinite money and wants the most polished UI/UX they can get. But there's some irony here: In most respects, the Google screens are quite simple, and nothing "jumps around" either during loading or usage. And the loading is fast.

For sending one of my screens, I need send only 400,000 bits; so, my screens should send and load quickly.

I'll consider semantic tags. Thanks.

Yes, multi-page forms could be a bummer; each of my forms fits easily on just one page. But my UI is just dirt simple for the user.

For

> old hardware and software

I'm not sure what I'm running is too old to matter. But if there are such users, then maybe they will like my pages because I suspect that the pages will look fine in any browser up to date as of 5, maybe 10, years ago.

> It's not hard to go overboard with modern web tech

That's an impression I got.

I've had a related point: Let's compare, say, the Microsoft Word UI and Web page UIs of, say, 10 years ago. Then, the Word UI can take weeks to master, for just that one program, more for Excel, more for Outlook (I finally found how to increase the font sizes, etc. in Outlook), while there were tens of million of Web sites 1+ billion people could use right away. Why? Because all the sites were simple and similar. Lesson: If Web programming offers as much opportunity for unique UIs, then we could lose the big advantage of the Web that anyone can use any page quickly. If that happens, then I want to vote with the majority and let others have unique UIs.


I certainly agree that some (probably most?) web pages have way more UI logic than they need to present the information to the user. Loading animations, back-to-top buttons, fixed position headers, social-share bars, and so many more UI components are totally unnecessary.

However CSS does have an important place even in the most basic presentation of information: proper styling can vastly improve readability. Especially on mobile devices where the layout must change to fit the device and a fixed 800px is totally unacceptable. This adaptation to fit the device is what sets webpages apart from more rigidity constrained types of documents.

Also, there's some degree of artistic expression in a nicely designed webpage... It's beside the point of why extensive styling capabilities are "needed", but that's part of why they're so popular.


> Especially on mobile devices where the layout must change to fit the device and a fixed 800px is totally unacceptable.

Why? Why should "the layout ... fit the device" -- I'm not trying to fill the user's screen; I don't want to fill the user's screen.

The smallest iPhone screen size I see is 320 × 480 pixels. With the horizontal scroll bars, the 320 pixels would be usable, and if the Web browser would permit using the 480 pixels for the 800 pixel width of my pages, then that would be even better. Some of the other iPhone resolutions are 750 × 1334, 1242 × 2208, and 1080 × 1920 pixels, and there my pages 800 pixels wide should look nearly perfect.

What's the problem? I'm not seeing a problem?

I'm trying to learn. Where am I going wrong? What am I not seeing?


> With the horizontal scroll bars, the 320 pixels would be usable Try reading an article while operating a horizontal scrollbar... it's a horrible experience because every line requires you to scroll from left to right, and then back to the left.

Also, your 800px page will still have a horizontal scrollbar on those devices because they're rendered at 2-3x, making the effective pixel-width of an iPhone 300px-400px. They could just zoom out really far and then use a magnifying glass to read it... thanks to the high resolution that would be possible, but it still wouldn't be pleasant.

> I'm trying to learn. Where am I going wrong? What am I not seeing? Try visiting your site on a smartphone, a TV, a tablet, etc... you'll see the issue.


> Why bother?

You're basically asking why half of us bother doing our jobs. It's not that you're criticizing; it's that you're cheerfully insulting people while pretending to be inquisitive about something you have no interest in learning about.

You don't care about this? That's great. Don't care. The people who built it aren't asking you to care.


It's not personal; it's just Web page coding.

I am "interested in learning", and that's exactly why I'm asking.

If you are writing complicated code for Web pages, then maybe you have some reasons wby -- I was asking for your reasons.

If such Web page functionality is your job, then the question would be, why?

My Web pages at 800 pixels wide should look fine on any screen I can think of, although maybe on some really small screens some use of horizontal scroll bars might be needed.

On a large screen on a desktop computer, just see all 800 pixels at once, and still my Web pages don't take up much room on the screen; I'm not trying to fill the screen and I'm guessing that that's a UX advantage.


I'm not sure if you're serious, and I think that's why nobody is stating the obvious - not everyone is building the same thing as you. There is not a chance in hell my company could get away with using just plain html. We have an interactive site, with a large team, with multiple workflows, client libraries and inter-connected dependencies. You're asking a really silly question, just because you made a shack in your backyard does not equate to making a house, then asking the home builders, "I made my entire shack out of wood and nails, why can't you make your house like that?"


What I've built looks like a Web site to me; the pages look quite usable.

"Client libraries" -- wow.

"Interactive" -- my Web site is interactive: I wrote a session state store, have two more back end servers, and have SQL Server. The server side is plenty complicated, but the client side is quite simple, and I'm still missing why the client side situation should often be otherwise.

Or, what the heck is wrong with just HTML, some CSS for a little convenience, and some JS if necessary? HTML has the basics: Tables, links, one line text boxes, multi-line text boxes, text, images, etc.

Pull-downs and roll-overs -- as a user I don't like them, so as a programmer I'm not using them. Anything that covers up what's on the screen I don't like for anything less important than announcing nuclear war.

With high irony, we're quite productively using HN with simple HTML, no pull downs or roll overs, nothing or next to nothing in icons (I hate icons), and, I just had Firefox save this HN page, some HTML with only a little JS with the HTML, two GIFs, 65 lines of CSS that looks nicely simple, and nothing else. Works fine.

I would think that the "dependencies" would be handled on the server side with some help from, say, in real time a session state store and/or for longer term a database.

For CSS, it finally dawned on me: There can be another place to put such cases of commonality -- the code that writes out the data to be sent to the client. I'm doing some of that and, then, using the classes in Microsoft's ASP.NET to generate the data sent to the client. So, to change fonts, colors, change the color for every other line of a table, etc., just do that in the code that calls the ASP.NET classes.

Heck, if want, change the colors of lines in the tables based on the phases of the moon, the temperature where the user's IP address is, for each time they see a new copy of the page, with no reds next to greens if know that the user is male (25% of the male population is partially red-green color blind, including me), etc. Try that in CSS!

Generally server side programming is easier than client side programming because (1) on the server have access to about all there is in computing and (2) on the client are throttled by, ugh, JS and, still, can't really see the stuff run.

For what bytes I'm sending to the users, I'm trying to keep that simple. I'm losing why it should be complicated, say much more complicated than just HN, or, really, why the CSS that is the subject of this thread is such an aid. Or, for generating what the user sees, I'm using essentially Microsoft's most powerful programming language, the .NET version of Visual Basic (C# is different mostly only just in syntactic sugar) -- gotta be a lot more powerful than JS on the client or CSS.

Why send complicated stuff to the clients? Why program in JS unless really have to? Why try to make new features of CSS ways to write software? What's so important to do that often need JS instead of just HTML?

Again, I'm trying to learn.


I'm just going to reply to a couple points on JS: We write code that runs on the client-side primarily for performance. Rendering without needing to send more data over the network or run more code on our servers is a huge win... Especially when we're not building traditional "web pages", but rather full web-apps - requiring fairly complex UI and business logic.

Plus, JS isn't something to be avoided these days. Its become a full-featured language and is as powerful if not more powerful than .NET


For my site, I'm just going for "traditional web pages".

Sure, it did occur to me that I could program my site so that the user saw only one URL and that URL would keep changing as appropriate for the user's dialog. A few minutes after I noticed that possibility, I gave it up. Sure, with that possibility, maybe the big deal would be write nearly all the 'logic' in JS to run on the client, with a lot of AJAX threads, using the server as a remote database or some such. Okay, if you want to do that. I'm not sure I've seen many such Web sites. Maybe someday I will want the architecture of my site to be like that, but for now I'm staying with tradition.

And for using a lot of JS on the client, I'd be concerned about the ability of a lot of advanced JS to do what I wanted, reliably, on all the mobile to desktop computers in the world; instead I just want to send some simple HTML, a little CSS, and maybe some minimal JS that Microsoft writes for me, which will be okay, I hope.

Okay, good: As long as I'm staying with a traditional Web site architecture, without JS I'm not missing much. Good to know. I'll conclude the same about version n + 1 of CSS.

Gee, I'm learning!


> Especially when we're not building traditional "web pages", but rather full web-apps - requiring fairly complex UI and business logic.

I think that is the main point. For many traditional web pages, there are not many reasons to really require a lot of JS or so.


Thanks! Would have taken me a long time to have been sure about that. So, I'm learning!


As a front end developer, I think it is easier and more maintainable to use styles for the appearance, and JavaScript for the behavior...

That being said, I find the complexity of many designs (CSS or JS driven) more distracting to users.

Now, for marketing sites, built by designers, CSS is likely going to be much better for performance. If the JS works as intended. Designers benefit from not having to be focused on programming.


> JavaScript for the behavior..

What "behavior"? Are you implementing an on screen calculator, some word whacking software, the game of Nim, chess, checkers, a drawing program using some HTML5 scalable vector graphics (SVG), all in JS on the client side? Okay.


You definitely don't create website on a professional level. If you want to build hobby websites with a fixed width of 800px as it is 1995... that's up to you. Complicated webpages don't have to be slow... if you landed on such one, then you've landed on a website created by an amateur.


You keep bringing up your sites that seem to work great everywhere. Care to share one?


That my Web pages should work nearly everywhere is not a big deal. Instead, it's simple. Except for a little JavaScript Microsoft writes for me, I'm just using some simple, old HTML with a little CSS. What goes to the client is, for the Web, just dirt simple.

Then each Web page is exactly 800 pixels wide, small screen, big screen, small window, big window, Internet Explorer, Firefox, Chrome, etc., all the same exactly 800 pixels wide, period. There are both vertical and horizontal scroll bars. The content of the pages is really simple, basically just some text, a simple PNG image, some links as at the top of these pages at HN, some simple, standard HTML controls, and nothing else. As I recall, the fonts are all 35 pixels high, that is, relatively large fonts. All the layout is with just HTML tables -- I'm not asking the Web browser to position or scale anything. No roll overs, pull downs, pop-ups, icons -- HN doesn't have such either.

So, on any browser window with at least 800 pixels of width, my Web pages should look fine; some users may want to use some magnification option in their Web browser -- I'm not going to program that logic. Simple. Dirt simple. No doubt. That my Web pages take up only 800 pixels of width on some workstation screen 4000 pixels wide is okay with me.

If my site has any value, then it's not in fancy HTML, CSS, or JavaScript. Same for HN.

I can understand that for a lot of sites, there is client side JavaScript that keeps looking at the size of the browser window and walks some tree of the document object model or some such and dynamically positions text, ads, images, video windows, etc. That could get complicated on one computer and much worse on a billion computers from smartphones to workstations. For solving that problem, I didn't figure out how or even attack it. If you are working on such a problem, you have my sympathy; if you get a good solution, you have my congratulations.

What I'm doing is dirt simple; no doubt you could have done it easily except for just one issue: Do you want such a simple Web page? HN does. Some other sites do. So do I.

But, yes, when my site goes live, I'll eagerly announce on HN. Then you can all say that my Web pages look like they were designed by 5 year old child in 1995 in 15 minutes after stealing five beers from his parents' refrigerator -- will be about right. Even more likely, by a drunk, baby T Rex. I'm not trying to build a brick outhouse or use a $3 million Ferrari to get six loaves of bread and three gallons of milk. Instead, simple as possible but not simpler.


So far the sites are not connected to the Internet. When they are, I will eagerly announce on HN.


I've read the ":NTH-OF-M-CHILD" section about five times through now and I still don't understand what objects you're trying to select or why. A clearer explanation would be helpful.

"For example, we can style the third element, if and only if it’s one of five children:" That makes sense, except your example has a red background, not a green one, and for some reason the 9th row has a red tile, which doesn't match your requirement that it be "one of five children". Very confusing.


If you look at the source for that example, he actually has 2 selectors that set an item to red, corresponding to the 3rd item in a group of 5 and the 7th item in a group of 9 (Formatted here for legibility):

    span:nth-child(3):nth-last-child(3){
        background-color:red !important;
    }

    span:nth-child(7):nth-last-child(3){
        background-color:red !important;
    }
That threw me for a bit of a loop too. "Wait, is that second item supposed to be red?" It would be clearer if the example and the demo matched up.


Thanks for the feedback -- that wasn't clear and I'll update the example and text to be clearer.


There's a typo too, 'adjacant' for 'adjacent'. I spent a moment wondering what adjacant meant.


Thanks, that's also fixed.


In his example image gallery, the image heights are all slightly different, which looks a bit jarring.


That was a result of downloading slightly different image sizes from placekitten so they weren't all the same image -- I'll resize them all to 640x480 to fix that.


Ok, I was wondering if it wasn't a rendering bug that was somehow caused by the CSS, which would have been bad.


In the example, I'd suggest to make 4th with 2x2 big pics, like 7th and 10th.


Oh, joy. A feature intended to allow making alternate rows in a table different colors is being abused for general programming. Remember where the C++ template mess took that language. Don't go there.


You consider sanely styling the layout of images to be general programming?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: