Wow. This is quite possibly one of the biggest breakthroughs I’ve made in quite some time. I’ve discovered CSS2 attribute selectors. As you may or may not know there are several ways to apply a CSS style to an element; you can add a class attribute to the element, define a CSS style that effects that particular element (all <b> tags having the same style, for example) and you can also based a style on the ID (id=â€?fooâ€?) of a given element. All of these are great but I’ve ran into cases where I wished that I could apply styles in other ways. Here’s an example.
Let’s say that I want to apply a particular style to any image that has the border attribute set to 1 (border=â€?1â€?). I could setup a class called ‘one_px_border_img’ and apply that to all of the images that have a border, which is how I might have done it before. However, as I’ve discovered, there’s a much more efficient way to do this using attribute selectors. Let’s take a look.
Give all images with border=�1� a 1px solid black border
img[border=�1�] {
border: 1px solid black;
}
When we hover the mouse over an image thats inside of an <a> tag change the border color
a img[border=�1�]:hover {
border: 1px solid red;
}
There are also some other attribute selectors that are worth noting:
Add a green border to images with an alt tag
img[alt] {
border: 1px solid green;
}
Apply a style to images with one or more of the list of classnames
img[class~=�classname1 classname2�] {
// style
}
This is big. It allows us to base CSS styling on the tag attributes of the elements themselves rather than adding a class=�� attribute or something similar.
Leave a Reply