2

Does anyone know what I am missing to vertically align a img inside a div?

I have some sass, though I can work with plain CSS too.

I thought text-align was sufficient ? But it isn't working. The margin and height are automatically set on the <img> so G know that is working.

.testdiv {
  font-size: rem(12);
  height: 80px;
  img {
    margin-left: 12px;
    height: 16px;
    width: 16px;
    text-align: center;
  }
}

and some html

<div class="testdiv">
    <img src="./test.png">
</div>
halfer
  • 19,824
  • 17
  • 99
  • 186
Martin
  • 23,844
  • 55
  • 201
  • 327

2 Answers2

2

You can use display: table-cell css property to vertically align an element inside a parent.

.testdiv {
  vertical-align: middle;
  display: table-cell;
  font-size: rem(12);
  text-align: center;
  background: black;
  height: 80px;
  width: 100px;
}

img {
  vertical-align: top;
  height: 16px;
  width: 16px;
}
<div class="testdiv">
  <img src="images/image.jpg" alt="Image Description">
</div>
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
1

see here jsfiddle

text-align has nothing to do with vertical-align

there are a number of ways to vertical-align items, one of them is display:flex

code :

.testdiv {
  font-size: rem(12);
  height: 80px;
  display:flex;
  align-items: center;
  justify-content: center;
  width:100px;
  height:100px;
  border:5px solid red;
      img {
        margin-left: 0px;
        height: 16px;
        width: 16px;
        text-align: center;
  }
}
Mihai T
  • 17,254
  • 2
  • 23
  • 32