简体   繁体   English

HTML:将div的内容水平和垂直居中?

[英]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. 我有一个包含一些内容的div,我希望这些内容在垂直和水平方向上居中。 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. 如果我删除display: table-cell ,它们将水平居中,但要对齐到顶部。

<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. 您可能还有另一个具有更高特异性的CSS声明。 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. 本文可能也有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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