I am writing this article because I feel like we are focusing more and more on JS in the front-end world. Forgetting about CSS and HTML possibilities.
In this piece, I’ll cover some CSS selectors starting with a child selector and hope to finish with some more surprising one. Enjoy
CHILD SELECTOR
Direct child selector only identifying p elements that fall directly within an article element.
article > p {…}
GENERAL SIBLING SELECTOR
General sibling selector selects elements that follow and shares the same parent. H2 the element must come after p element.
p ~ h2 {…}
ADJACENT SIBLING SELECTOR +
Adjacent Sibling Selector selects the element that directly follow and shares the same parent
Only p elements directly following img element will be selected.
img + p {…}
ATTRIBUTE SELECTORS
Attribute selectors select an element based on the presence or/and value of given attribute. There are several types, examples below.
Selects all elements that have alt attribute.
divalt {...}
Selects all elements that have alt with exact value.
divalt=”something” {…}
Selects elements that contain value but in selector also exact value. (simply needs to have the something anywhere in the value of the attribute)
divalt*=”something” {…}
Selects elements that start with a selector value.
divalt^=”something” {…}
Selects elements that end with a selector value.
divalt$=”something” {…}
DIV:NTH-LAST-CHILD(2) {…}
Selects the last two div, they have to be siblings/share same parent
:NOT(:LAST-CHILD) {…}
Selects all elements which are not the last child. Combination of :not and :last-child.
DIV:FIRST-OF-TYPE {…}
Select the first siblings of its type.
Hope that helps. Please share your most interesting selectors in comments!
Top comments (0)