CSS Selectors You Might Not Know About

Chris Sevilleja
💬 comments

CSS has some great selectors built in that some people don't know about. Learning about these can make life easier when styling your webpages. For instance, you can select the even and odd elements, the first and last, the siblings, and so much more. In this article we'll go through different scenarios of CSS selectors and how to use them. We won't dive into the known selectors like choosing by ID and class, but we'll just go through some under the radar selectors.

Let's get started with the selectors. For the simple selectors, we'll just explain how they work. For the more advanced ones, you'll see a Codepen of the selector in

First Line and First Letter

p:first-letter Style just the first letter in the paragraph
p:first-line Style just the first line in the paragraph

See the Pen peHtI by Chris Sevilleja (@sevilayha) on CodePen

Table of Contents

    Before and After

    :before Add elements before the current element using content in CSS
    :after Add elements after the current element using content in CSS

    See the Pen ugaKi by Chris Sevilleja (@sevilayha) on CodePen

    Siblings and Children

    body > p Select p tags that are only immediate children (can't be nested)
    h1 + p Select the p sibling immediately following the h1 tag
    h1 ~ pre Find all pre that follow the h1 tag

    Target Pseudo Class

    Style a Specific Target :target

    Selector URL Div
    *:target http://example.com/about.html#thebox
    stuff in here styled

    This one's pretty cool. If somebody accesses your site using http://example.com/about.html#thebox, :target will style the div with ID of thebox.

    This could definitely be used when you are trying to link to a specific comment on a page and want to highlight it.

    :nth-child Pseudo Classes

    tr:first-child / tr:last-child First or last rows
    tr:nth-child(odd) / tr:nth-child(even) Choose every odd or even rows
    tr:nth-child(10n-1) Every 9th, 19th, 29th, etc element
    tr:nth-child(-n+6) First 6 rows of a table
    tr:nth-child(-n+6) First 6 rows of a table

    Attribute Selectors

    [attr~="value"] a[rel~="copyright"] Any elements with "value" in a list of attributes separated by white spaces
    [attr|="value"] a[hreflang|="en"] Attribute value begins with and/or is followed by a dash. This will also select en-US, en-scouse, and anything that begins with en
    [attr^="value"] img[src^="images/"] Values begin with a certain string
    [attr$="value"] a[href$=".html"] Values end in a certain string

    So Many More

    CSS has so many more selectors that aren't covered here. There are things like :nth-of-type. View the full selectors at the official W3 Site.

    Chris Sevilleja

    173 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.