我想用一个视差背景图像水平和垂直居中一个div。我尝试过bootstrap 4
类d-block
,mx-auto
,text-center
。它水平居中但不垂直居中。我怎样才能将它垂直居中?
.parallax_bg {
background: url(assets/img/corinne-kutz-211251.jpg);
background-size: cover;
height: 100%;
min-height: 100%;
overflow: auto;
}
.parallax {
background-attachment: fixed;
background-size: cover;
background-repeat: no-repeat;
}
.parallax_text > p {
font-size: 20px;
}
<section data-stellar-background-ratio="0.5" class="parallax parallax_bg text-center mx-auto d-block">
<div class="parallax_text">
<h3><em>Venenatis Nisl Porta</em></h3>
<p>Lorem vestibulum gravida ipsum non velit aliquam</p>
<a class="btn btn-primary mt-3" href="#">Read More <i class="fa fa-angle-double-right" aria-hidden="true"></i></a>
</div>
</section>
只需将position: relative
应用于parallax
类,然后将以下css应用于parallax_text
类:
.parallax_text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
您可以像这样尝试flex:
.parallax_bg {
background: url(https://lorempixel.com/400/400/);
background-size: cover;
height: 100%;
min-height: 100%;
overflow: auto;
}
.parallax {
background-attachment: fixed;
background-size: cover;
background-repeat: no-repeat;
height: 120vh;
display: flex;
justify-content: center;
align-items: center;
}
.parallax_text {
background: #fff;
}
.parallax_text>p {
font-size: 20px;
}
<section data-stellar-background-ratio="0.5" class="parallax parallax_bg text-center mx-auto d-block">
<div class="parallax_text">
<h3><em>Venenatis Nisl Porta</em></h3>
<p>Lorem vestibulum gravida ipsum non velit aliquam</p>
<a class="btn btn-primary mt-3" href="#">Read More <i class="fa fa-angle-double-right" aria-hidden="true"></i></a>
</div>
</section>