0

It's a very common situation: a designer tells me that some piece of text should be vertically centered, but I can't use the display:table-cell; hack because the containing element needs to have a different display property. I also don't want to have to use any position:absolute due to the problems that presents.

Fiddle: https://jsfiddle.net/z824m656/1/

HTML

<div class="contents-vertically-centerd">
  <img src="https://blog.stackoverflow.com/images/wordpress/stackoverflow-logo-300.png" width="150"/><span>Here's some text that I want vertically centered with respect to the image</span>
</div>

CSS

div.contents-vertically-centerd { padding: 10px; border: 1px dashed #000000; }
Subpar Web Dev
  • 3,210
  • 7
  • 21
  • 35
  • 1
    Possible duplicate of [How to align text vertically center in div with CSS?](http://stackoverflow.com/questions/8865458/how-to-align-text-vertically-center-in-div-with-css) – random_user_name Feb 02 '16 at 18:03

5 Answers5

1

You need to vertically align the image, not the text.

Have you tried:

div img {
vertical-align: middle;
}

In the kind of situation you describe, it will also assist you if you:

  • explicitly declare the height of the image
  • declare the display of the <span> text as inline-block
  • explicitly declare the height of the <span>
  • explicitly declare the line-height of the <span>
Rounin
  • 27,134
  • 9
  • 83
  • 108
0

Here's an updated fiddle using vertical-align: middle; https://jsfiddle.net/z824m656/2/

div.contents-vertically-centerd * {
  vertical-align:middle;
}
fnune
  • 5,256
  • 1
  • 21
  • 35
0

You can use vertical-align: middle but keep in mind this only aligns inline (or inline-block content). So it should go like:

div.contents-vertically-centerd img, div.contents-vertically-centerd span {
    display: inline-block;
    vertical-align: middle;
}
Anton
  • 2,458
  • 2
  • 18
  • 30
0

For your special use case, there’s a simple solution: Use vertical-align: middle on the image. It will center the text to the image. Here’s the updated Fiddle.

Joshua Gleitze
  • 807
  • 1
  • 9
  • 12
0

Another option is the transform: translateY(-50%) method.

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

div {
  height: 200px;
  
  /* Used to center horizontally */
  text-align: center;
}

p {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
<div>
  <p>This text is vertically centered.</p>
</div>

A more detailed write-up here.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184