user4035
user4035

Reputation: 23759

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

Upvotes: 0

Views: 1359

Answers (2)

Temani Afif
Temani Afif

Reputation: 274069

A solution is to use flex and justify-content:space-around and remove margin:

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

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

#block1 {
  background: orange;
}

#block2 {
  background: magenta;
}
<div id="wrap">
  <div id="block1"></div>
  <div id="block2"></div>
</div>

Upvotes: 1

JasonB
JasonB

Reputation: 6378

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>

Upvotes: 0

Related Questions