Consider this HTML:
<body style="max-width: 50px; border: 1px solid black; margin: 0 auto;">
<p>This is some text</p>
<div style="width: 100px; background: yellow">
<p>Some wider content</p>
</div>
<p>Some more narrow text</p>
</body>
I want to centre the yellow box so that it overflows the body
. I’ve looked at many many answers on StackOverflow how to do this and then generally involve setting the div
to relative positioning and wrapping it in another div, but then you always need to set the height of the wrapper div explicitly.
Is there a way to centre the div horizontally without affecting how the vertical layout works?
Also note, I do want to centre it; not just offset it by a fixed amount.
2
Answers
You could use flexbox. Note that this will change the way that margins interact with children.
Use the following settings on that div:
That moves the div to the right by 50% of the parent’s width and then moves it back left by 50% of its own width, thereby centering it horizontally.
position: relative;
is necessary to make these settings have an effect at all.Note that using
position: relative;
still preserves the (horizontal) space the div takes in the document flow, which would not be the case when usingposition: absolute
.