我以前使用flexbox進行垂直對齊,但對於我在對齊時非常偏離中心的位置使用它的元素,特別是對於下面的JSFiddle示例中的div ,其中向包含文本其餘部分的同一個div添加按鈕會使對齊太低。Flexbox CSS垂直對齊不完全中心
代碼:
#servicesGrid {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.service {
width: 24.85%;
height: 45%;
background: #262626;
display: block;
float: left;
margin: 0 0.2% 0 0;
text-align: center;
}
#servicesGrid .service:nth-of-type(1) {
width: 100%;
margin: 0 0 0.2% 0;
height: 80%;
}
#servicesGrid .service:nth-of-type(5) {
margin-right: 0;
}
.serviceContent {
margin: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
color: #fff;
text-align: center;
}
.button {
color: #fff;
border: 2px solid #fff;
border-radius: 15px;
padding: 10px 20px 10px 20px;
text-transform: uppercase;
font-family: 'Effra-Regular';
text-decoration: none;
transition: all linear 0.3s;
-webkit-transition: all linear 0.3s;
-moz-transition: all linear 0.3s;
}
.button:hover {
color: #000;
background: #fff;
}
<div id="servicesGrid">
<div class="service">
<div class="serviceContent">
<div style="margin-left:auto; margin-right:auto">
<h1 style="font-size:40px; font-family:'Effra-Light'; margin-bottom:-10px">Service</h1>
<h4>Lorem ipsum dolor sit amet</h4>
<br/>
<a href="#contactUs" class="button" alt="Find Out More Button">Find Out More</a>
</div>
</div>
</div>
</div>
的jsfiddle:https://jsfiddle.net/f92udw9v/2/。
Flex對齊通過在容器中分配空閒空間來工作。如果你有一個單一的項目居中,這不是一個問題。但是,如果添加第二個項目,則會造成不平衡。現在你的對中關閉了,因爲一邊有更多的「重量」。您可以通過配重或使用絕對定位來平衡它。這些方法在此處詳述:[在flexbox中的絕對定位](http://stackoverflow.com/q/36191516/3597276)。 –
你有不同的高度,分別爲100%,45%和80%。很難理解你想要達到的目標。你是否希望它在屏幕高度80%的div內垂直居中? – SomeGuy