如何在div中垂直对齐h2元素?

时间:2014-08-25 12:03:08

标签: html css

我这里有codepen,有人知道如何垂直和水平地将h2对齐到div元素的中心吗?

HTML

<div class="container">
   <h2 class="center">
      Hello World!
   </h2>
</div>

的CSS:

 .container {
position:relative !important;
height: 100%;
margin: 0 auto;
 display:table;
}

.center {
text-transform: uppercase;
text-align: center;
z-index: 200;
position: absolute;
  vertical-align:middle;
font-size: 4em;
margin: 0;
padding: 1em .75em 0 .75em;
line-height: .8;
text-shadow: 1px 1px 10px #666666;
  display:table-cell;
}

3 个答案:

答案 0 :(得分:0)

删除positoin个属性,并为100%body应用html

body,html{height:100%; padding:0; margin:0;} 
.container {    
height: 100%;
margin: 0 auto;
padding:0;
 display:table;
}

.center {
text-transform: uppercase;
text-align: center;
z-index: 200;    
vertical-align:middle;
font-size: 4em;
margin: 0;
padding:0;
text-shadow: 1px 1px 10px #666666;
display:table-cell;
}

DEMO

答案 1 :(得分:0)

有一个更好的解决方案。 但这也是一个:

.container {
    height: 100%;
    border: solid thin #000;
}
body,html{
    height: 100%;
}
.center {
    border: solid thin #ddd;
    text-transform: uppercase;
    z-index: 200;
    position: absolute;
    display: inline-block;
    text-align:center;
    left: 25%;
    right: 25%;
    top: 25%;
    bottom:25%;
    font-size: 4em;
    line-height: .8;
    text-shadow: 1px 1px 10px #666666;
}

答案 2 :(得分:0)

display:flex;可能是一个设置很少CSS的提示: http://codepen.io/anon/pen/mEufx

html,body {
  height:100%;
}
.container {
  min-height:100%;
  display:flex;
}

.center { 
  margin:auto;
  text-transform: uppercase;
  font-size: 4em;
  text-shadow: 1px 1px 10px #666666;
}
相关问题