skip to Main Content

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


  1. You could use flexbox. Note that this will change the way that margins interact with children.

    body {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    <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>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search