Margin auto doesn't work as I expected
I am trying to put
.left
and .right
elements evenly within .header-content
using margin: 0 auto
. When I apply the rule, it doesn't do anything, why?
HTML:
CSS:
9 Replies
divs by default have 100% width, so that
0 auto
gets translated to 0 0
. auto margin only works when you have a set (max-)width
on your elementBut I've actually set
width: max(1200px)
on the parent element (.header-content
). I don't get itYeah, and the child elements take up 100% of that width
You have to set the size on the children, otherwise there's no room for the margin
But they're display is inline-block, it means they're width should be fixed (IIRC). If I inspect both elements, they have exact width
why inline block? just make the .header-content
display:flex
with justify-content: space-between/space-around
also width: max(1200px)
does nothing, it will just make it 1200px all the time.
you probably want it to be max-width: 1200px;
and don't set a height on header. let the content determine the height. (use padding-block if you want some vertical space)I purposefully don't want to use flex here, because I want to train my understanding of margins
Ah, I forgot what it does, yeah
Thanks
So, I put
display: flex
on the .header-content element, but still kept auto margins, and now it works. Why margin: 0 auto
and margin-left: auto
don't work when .left and .right are inside a block
element display but work when they're inside flex
element?
This is counterintuitive to me right now. I thought auto margins work whenever parent has a specific width setinline blocks and auto margins are not a thing
when becoming a flex/grid child it's okay
Then I'm really confused over when margin auto works and when it doesn't
wanted to try to explain it myself. but think this SO answer does it better
ref: https://stackoverflow.com/questions/19076919/marginauto-doesnt-work-on-inline-block-elements