Remove the margin from the last block element in CSS
May 28, 2021
We can remove the margin from the last element if it is a block item by using the :last-child
CSS pseudo-class. This selector allows us to target the last element directly inside its parent container.
By using this selector we can avoid adding a class on it in order to remove for example its margin-bottom
.
How does it work?
Let's say you have many paragraphs inside a main
element and you want to remove the margin-bottom
from the last element. You can use select the last paragraph by using the last-child
pseudo-class, like below:
main *:last-child {
margin-bottom: 0;
}
Code example on CodePen
I've created an example on CodePen, you can check the code here or play around with it below.
Your JS is turned off. Please turn it on to see the CodePen. Here's a screenshot from the Pen
Try reload the page, our check out the pen on CodePen.