简体   繁体   中英

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

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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM