Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Centre a fixed-width variable-height div horizontally so it overflows its parent

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Also note, I do want to centre it; not just offset it by a fixed amount.

>Solution :

Use the following settings on that div:

position: relative;
left: 50%;
transform: translateX(-50%);

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 using position: absolute.

body {
  max-width: 50px;
  border: 1px solid black;
  margin: 0 auto;
}

div {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  width: 100px;
  background: yellow;
}
<body>
  <p>This is some text</p>

  <div>
    <p>Some wider content</p>
  </div>

  <p>Some more narrow text</p>
</body>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading