Subpar Web Dev
Subpar Web Dev

Reputation: 3280

Is there a good way to vertically center text without using display:table-cell on the parent?

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; }

Upvotes: 0

Views: 37

Answers (5)

Brett DeWoody
Brett DeWoody

Reputation: 62851

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.

Upvotes: 0

Rounin
Rounin

Reputation: 29491

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>

Upvotes: 1

Joshua Gleitze
Joshua Gleitze

Reputation: 927

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.

Upvotes: 0

Anton
Anton

Reputation: 2646

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;
}

Upvotes: 0

fnune
fnune

Reputation: 5514

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

div.contents-vertically-centerd * {
  vertical-align:middle;
}

Upvotes: 0

Related Questions