I noticed that there is very little spacing between the AboutDogs
and AboutCats
divs. So I added some padding-top: 20px
to the AboutCats
to create some space between AboutDogs
and AboutCats
.
But let's say there is a scenario where I have only AboutCats
and there is no other div on top of it. In that case, I don't want to add the padding-top: 20px
since that will be unnecessary spacing on top.
<div >
<main>
<div ></div>
<div ></div>
</main>
</div>
Is there a way to address this scenario using CSS?
CodePudding user response:
This is what the adjacent sibling selector is useful for.
You have some errors in your HTML code, by the way:
- Don't have a space between
class
and the equals sign - Remember to close tags, as your
main
tag isn't closed
Here is an example of the adjacent sibling selector in use for you:
main {
background: lightgrey;
padding: 2em;
}
.about {
border: 1px solid red;
}
/*
* Adjacent sibling selector to add a top margin to any
* element with .about which follows another .about
*/
.about .about {
margin-block-start: 1em;
}
<div >
<main>
<div >Lorem</div>
<div >Ipsum</div>
</main>
</div>
This is also very useful for setting up spacing on typography elements, such as paragraphs which follow another paragraph or a heading.
You also could have done this using CSS grid or flex, combined with the gap
property. Here's an example:
main {
background: lightgrey;
padding: 2em;
display: grid;
grid-template-columns: 1fr;
gap: 1em;
}
.about {
border: 1px solid red;
}
<div >
<main>
<div >Lorem</div>
<div >Ipsum</div>
</main>
</div>
CodePudding user response:
One modern solution which also is redundant for all potential cases is the usage of Flexbox. Change the flex-direction
to column
to maintain the normal block-level behavior. You can space apart elements within Flexbox by using the gap
property.
main {
display: flex;
flex-direction: column;
gap: 20px;
}
/* for visualization only */
main > div {
border: 2px dashed red;
}
<div >
<main>
<div >About Dogs</div>
<div >About Cats</div>
</main>
</div>
An Alternative is the usage of the :nth-child()
selector. With n 2
you can select all child elements starting from the 2nd element.
main > div:nth-child(n 2) {
margin-top: 20px;
}
/* for visualization only */
main > div {
border: 2px dashed red;
}
<div >
<main>
<div >About Dogs</div>
<div >About Cats</div>
</main>
</div>