The adjacent sibling selector allows you to target elements that are immediately preceded by another specific element.
Check your HTML code for these errors:
- Ensure there is no space between the class attribute and the equals sign
- Make sure to close all tags properly, like the main tag in your code
Here's an example demonstrating the usage of the adjacent sibling selector:
main {
background: lightgrey;
padding: 2em;
}
.about {
border: 1px solid red;
}
/*
* Using the adjacent sibling selector to add margin to
* .about elements following another .about element
*/
.about + .about {
margin-block-start: 1em;
}
<div class="main-container">
<main>
<div class="about about--dogs">Lorem</div>
<div class="about about--cats">Ipsum</div>
</main>
</div>
This selector is particularly useful for creating consistent spacing between text elements like paragraphs or headings.
You could achieve a similar effect using CSS grid or flex properties along with the gap property. Here's an alternative example:
main {
background: lightgrey;
padding: 2em;
display: grid;
grid-template-columns: 1fr;
gap: 1em;
}
.about {
border: 1px solid red;
}
<div class="main-container">
<main>
<div class="about about--dogs">Lorem</div>
<div class="about about--cats">Ipsum</div>
</main>
</div>