2017-02-14 122 views
-3

我希望内容垂直和水平居中,但它只居中水平居中。问题是我没有固定的高度。 谢谢你们的帮助!居中水平和垂直的DIV没有固定高度

html, 
 
body { 
 
    height: 100% margin: 0; 
 
    overflow: hidden; 
 
} 
 
.content { 
 
    width: 100%; 
 
    height: 100%; 
 
    align-items: center; 
 
    justify-content: center; 
 
    display: flex; 
 
    flex-direction: column; 
 
    text-align: center; 
 
}
<div class="content"> 
 
    <h1>Welcome to the website!</h1> 
 
</div>

+0

你的html在哪里 –

+0

你肯定答案不能在这个线程中找到http://stackoverflow.com/questions/396145/how-to-vertically-center-a-div-for-所有浏览器? – Turnip

+0

谢谢,找到解决方案! – Daniel

回答

0

关注这个代码。

body{ 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 
.content-wrapper{ 
 
    background-color: #121212; 
 
    display: block; 
 
    left: 0; 
 
    height: 100%; 
 
    padding: 15px; 
 
    position: fixed; 
 
    top: 0; 
 
    width: 100%; 
 
} 
 
.content{ 
 
    background-color: #f5f5f5; 
 
    display: table; 
 
    height: 100%; 
 
    margin-left: auto; 
 
    margin-right: auto; 
 
    text-align: center; 
 
    width: 100%; 
 
} 
 
.centent-cell{ 
 
    display: table-cell; 
 
    height: 100%; 
 
    vertical-align: middle; 
 
    width: 100%; 
 
} 
 
h1{ 
 
    color: #121212; 
 
}
<div class="content-wrapper"> 
 
    <div class="content"> 
 
<div class="centent-cell"> 
 
    <h1>Welcome to the website!</h1> 
 
    </div> 
 
</div> 
 
</div>

1

可以轻松地居中在这样的元件,相对于父(假设父母有position: relative;)。

在您的例子:

h1 { 
    display: block; 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    transform: translate(-50%, -50%); 
} 

您也可以居中使用position: fixed;不是屏幕的中间。

0

这里有你所需要的一个例子:

<section> 
    <div class="centerize"> 
     <div class="v-center"> 
      <div class="box">Say my name!</div> 
     </div> 
    </div> 
</section> 

和CSS

section { 
    height: 100vh; 
    background: #fff; 
} 

.centerize { 
    display: table; 
    height: 100%; 
    width: 100%; 
} 

.v-center { 
    display: table-cell; 
    vertical-align: middle 
} 

.box { 
    background: #000; 
    width: 10%; 
    margin: 0 auto; 
} 
0

关注这个代码

HTML

<body > 
    <div class="content"> 
    <h1>Welcome to the website!</h1> 
    </div> 
</body> 

CSS

html,body { 
    height : 100%; 
    width : 100%; 
} 
.content { 
    height : 100%; 
    width : 100%; 
    display: table; 
} 
h1 { 
    text-align: center; 
    display: table-cell; 
    vertical-align: middle; 
}