Search code examples
htmlcsscentering

How to center inline-block element with margin


HTML:

<div id="wrap">
    <div id="block1"></div>
    <div id="block2"></div>
</div>

CSS:

div#wrap{
    margin-top: 3em;
    border: solid 1px black;
    text-align: center;
}

div#wrap *{
    display: inline-block;
    width: 12.5em;
    margin-top: 1em;
    height: 8em;
}

div#wrap *:not(:last-child){
    margin-right: 8em;
}

#block1{
    background: orange;
}

div#wrap #block2{
    background: magenta;
}

These 2 blocks are supposed to be centered in responsive design mode. When the screen is wide enough to have 2 blocks in a row, the code works. But when I narrow the screen down, the top block is shifted to the left because of the margin:

enter image description here

fiddle

Is it possible to fix this without media queries?

Edit

I tried flex-box:

div#wrap{
    margin-top: 3em;
    border: solid 1px black;
    display: flex;
    flex-flow: row wrap;
    justify-content: center;
}

fiddle2


Solution

  • If you use a container with negative margin, you don't need to vary the margin for the endpoints of the rows at different breakpoints and you can just go with inline-block. I set font-size to zero in the container so I can calculate my widths using percents without worrying about white space.

    div#wrap {
      margin-top: 3em;
      border: solid 1px black;
      padding: 20px;
      text-align: center;
    }
    
    .block {
      display: inline-block;
      width: 12.5em;
      margin: 20px;
      height: 8em;
      font-size: 16px;
    }
    
    .block-container {
      margin: -20px;
      font-size: 0;
    }
    
    #block1 {
      background: orange;
    }
    
    #block2 {
      background: magenta;
    }
    <div id="wrap">
      <div class="block-container">
        <div class="block" id="block1"></div>
        <div class="block" id="block2"></div>
      </div>
    </div>