DEV Community

arbarrington
arbarrington

Posted on • Updated on

CSS Attribute Selectors

// select all elements with a given tag name

body {
    background-color:rosybrown;
}
Enter fullscreen mode Exit fullscreen mode

// impacts all h1 elements when the mouse is hovering over them

h1.hover {
    color: purple;
}
Enter fullscreen mode Exit fullscreen mode

// 'nth' can be replaced with 'first', 'last', or 'only'. This selector will grab the second li element in the first list

li:nth-child(2) {
    color: steelblue
}
Enter fullscreen mode Exit fullscreen mode

// this grabs an element by its ID, and defines its properties as a link that has not been clicked

#google-link:link {
    color: blue;
} 
Enter fullscreen mode Exit fullscreen mode

// this allows us to identify which links have been visited by adjusting their properties after being visited. In this case, it is still only applying to the element with the google-link ID

#google-link:visited {
    color: darkblue;
} 
Enter fullscreen mode Exit fullscreen mode

// this will impact all links that follow a heading

h2 + a {
    color:aliceblue;
}
Enter fullscreen mode Exit fullscreen mode

// slightly different from the selector above, this will grab all buttons that follow a text area that they share a parent with

textarea ~ button {}
Enter fullscreen mode Exit fullscreen mode

// the > is the child selector, in this case grabbing all li's within a ul

ul > li {
    color:skyblue;
}
Enter fullscreen mode Exit fullscreen mode

// descendent selector, all children and their children

ul li {
    color:black;
}
Enter fullscreen mode Exit fullscreen mode

// all h2's with the subtitle class

h2[class=subtitle] {
    color: magenta
}
Enter fullscreen mode Exit fullscreen mode

// all images on page with sources linking to the parent directory*/

img[src^="../img/"] {
    border: 10px solid black;
}
Enter fullscreen mode Exit fullscreen mode

/replace ^ with * to contain the phrase anywhere in the string/

// all h2's with a class subtitle that may be found within a list of class names that are separated by white spaces

h2[class~=subtitle] {
    background: green
}
Enter fullscreen mode Exit fullscreen mode

// all h2's with a class subtitle that may be found within a list of class names and may have a dash(-) encasing the word rather than a space

h2[class|=subtitle] {
    font-size: 12px;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)