ab11
ab11

Reputation: 20100

HTML: center a div's contents horizontally and vertically?

I read a bunch of things to try, but still can't get this working. I have a div with some contents, I'd like the contents to be centered vertically and horizontally. When I do the below, they center vertically, but justify to the left. If I remove the display: table-cell, they center horizontally but justify to the top.

<div class='contents'>
  <span>a span</span><br>
  <span>b span</span><br>
  <span>c span</span>
</div>

.contents {
  height: 150px;
  text-align: center;
  display:table-cell;
  vertical-align:middle;
}

Upvotes: 0

Views: 84

Answers (2)

Jamie Barker
Jamie Barker

Reputation: 8256

You probably have another CSS declaration that has a higher specificity. Here's an example:

#container div {
  text-align:left;  
}
.contents {
  height: 100px;
  width:100px;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
  background: green;
}
<div id="container">
  <div class='contents'>
    <span>a span</span>
    <br>
    <span>splurge b span</span>
    <br>
    <span>c span</span>
  </div>
</div>

This article might help too.

Upvotes: 1

Thomas Theunen
Thomas Theunen

Reputation: 1274

I tried your example and this is working fine. Is it in a certain browser that it is not working for you?

.contents {
  height:100px;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
  background: red;
}
<div class='contents'>
  <span>a span</span>
  <br>
  <span>b span bit longer</span>
  <br>
  <span>c span</span>
</div>

Upvotes: 1

Related Questions