1 min read

CSS selector starts with

What Did I Google Today
Disclaimer:these posts are things I tend to Google more than once. Instead of testing my luck every time, I'm going to collect them here, for later.

Problem

I keep having to select similar elements on a page that have no unique Class (seriously, put some clothes on Meredith!) or ID. A generic input or p tag selector is too general. CMS’s or not being in control of the backend make it impossible for me to add something into the HTML.So my solution is to create CSS selectors that are more specific.

Solution

CSS has the option to select HTML elements via attributes. Which is amazing. A couple of examples.

HTML element has attribute

div[width] {
  background-color: yellow;
}

HTML element with an attribute with that exact value, like "select all links that go to my own website"

a[href="https://kenvandamme.be"] {
  color: orange;
}

HTML element with an attribute that start with a value, like "select all links that are external"

a[href^=http] {
  color: green;
}

HTML element with an attribute that ends in a value, like "select all images that have the jpg extension"

img[src$=.jpg] {
  border: 1px solid red;
}

HTML element with an attribute that contains a certain value, like "select all links that are either a phone or email link"

a[href*=mail][href*=tel] {
  color: red;
}
© 2023 Ken Van Damme
No 🍪 cookies, 💰 ads or ❗pop-ups.