tonio94
tonio94

Reputation: 510

Vertically center content of a inline-block div

I am trying to center horizontally and vertically the content of my divs. I found some threads explaining it, but it never fits well in my code.

There are 3 centered div (.block) in a another div (.container) which is also centered but on the screen. Content of blocks is not centered vertically. I tried to use line-height but I loose some text (out of block).

Here is my code :

.container {
    width: 70%;
    margin: 10px auto;
    position: relative;
    text-align: center;
    border: 1px solid black;
}

.block {
  background-image: -webkit-linear-gradient(150deg, #D7D7D7, #979797);
  background-image: -o-linear-gradient(150deg, #D7D7D7, #979797);
  background-image: linear-gradient(240deg, #D7D7D7, #979797);
  border-radius: 10px;
  height: 100px;
  width: 100px;
  display:inline-block;
  margin: 10px;
  padding: 10px;
  vertical-align: middle;
  line-height: 1.5;
}

<div class="container">
    <div class="block">Hello</div>
    <div class="block">Everybody</div>
    <div class="block">Would like to center it please</div>
</div>

I tried to put content in a p tag, it's better but still not centered.

Thanks.

Upvotes: 0

Views: 2419

Answers (1)

Johannes
Johannes

Reputation: 67768

You can do that with flex, both on the container and the items in it, using settings as shown below. In this case the text content of each container is automatically treated as a flex item, which makes the centering possible.

.container {
  width: 70%;
  margin: 10px auto;
  text-align: center;
  border: 1px solid black;
  display: flex;
  justify-content: center;
}

.block {
  background-image: -webkit-linear-gradient(150deg, #D7D7D7, #979797);
  background-image: -o-linear-gradient(150deg, #D7D7D7, #979797);
  background-image: linear-gradient(240deg, #D7D7D7, #979797);
  border-radius: 10px;
  height: 100px;
  width: 100px;
  margin: 10px;
  padding: 10px;
  vertical-align: middle;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="container">
  <div class="block">Hello</div>
  <div class="block">Everybody</div>
  <div class="block">Would like to center it please</div>
</div>

Upvotes: 3

Related Questions