I have a div with 4 child elements. Each child has a 5px margin on the bottom. I can't seem to add a larger margin-top to the last child (or equivalently, a larger margin-bottom to the preceding child). Check out my fiddle.
I've tried adding a top border and top padding to the last child, as well as changing the overflow settings of the container with no luck. Any tips?
#header {
display: flex;
flex-flow: column;
height: 100%;
box-sizing: border-box;
overflow: hidden;
}
#header div {
padding: 0;
margin: 0 0 5px 0;
}
#blurb {
margin-top: 50px;
}
<div id="header">
<div id="greeting">
content
</div>
<div id="title">
content
</div>
<div id="subtitle">
content
</div>
<div id="blurb">
content (top margin doesn't change!)
</div>
</div>
The issue is CSS specificity.
The selector #header div is more specific than the selector #blurb.
To be more precise, the selector #header div has a specificity calculation of 0, 1, 0, 1, whereas the selector #blurb is 0, 1, 0, 0.
You need to increase the specificity of the selector #blurb if you want it to override the other styling.
For instance: (updated example)
#header div {
padding: 0;
margin: 0 0 5px 0;
}
div#blurb {
margin-top: 50px;
}
The selector #header #blurb would work as well.
#header #blurb {
margin-top: 50px;
}
For what it's worth, you can also use the :last-child or :last-of-type pseudo-classes to select the last element:
#header div:last-of-type {
margin-top: 50px;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With