Table of contents
Have you ever heard of the lobotomized owl selector in CSS? Despite being a lesser-known selector, it can sometimes prove to be a useful tool in web development. Let's discuss this selector in depth.
Read this article on my blog
Understanding the Owl Selector
The owl selector that allows us to apply styles to any and all elements that have an adjacent sibling which they follow. The selector looks like this:
* + * {
padding-top: 15px;
}
The *
is the universal selector which allows us to select all elements in the DOM and style them. The +
is the Adjacent sibling combinator and is used to select the next sibling of an element, provided that they both have the same parent element. For example, in the following markup:
<div class="parent">
<h1>Heading</h1>
<p>Paragraph</p>
</div>
The paragraph comes immediately after the h1. So, we can select this paragraph tag like this:
/* Paragraphs that come immediately after the heading */
h1 + p {
color: red;
}
To put it simply, the owl selector applies styles to all elements in the document that follow/proceed other elements, provided they are on the same level. The illustration below may help clarify this concept:
In the above illustration, all three elements are on the same level (have the same parent element). The second and third elements have a preceding sibling. However the first element does not have a previous sibling so it will not be selected.
Usage
One of the most common use cases for this selector is to add spacing between sections and paragraphs in blog/content websites. For example, adding padding or margin between paragraphs. Traditional methods almost always have unwanted effects for this use case (for example, adding spacing after the last element or above the first element).
This is illustrated here:
The example above can be coded like this:
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
.parent > * + * {
margin-top: 1.5em;
}
.child {
width: 150px;
height: 50px;
background: red;
}
Other possible use cases could include:
- Apply a style to an element only when it comes after another element on the page.
- Add some spacing between rows in a table.
Nested Layouts
Another useful feature is that the owl selector works pretty well with nested elements, as illustrated below:
I hope you learned something new about CSS today!
Check out this article on my blog Thank you for reading