我正在使用CSS3的Viewport Height制作全屏部分(高度:100vh)。不幸的是,我遇到了在一个部分中水平和垂直居中元素的问题。我试图让第一部分中的图像和文本作为一组出现在屏幕中央。谢谢你的帮助!
http://jsfiddle.net/stybfgju/
HTML:
<section class="red-bg">
<div class="middle">
<img src="http://lorempixel.com/g/300/300/abstract/" alt="" />
<h1>Some text here.</h1>
</div>
</section>
<section class="blue-bg">
<p>Another section here.</p>
</section>
CSS:
body {
color: #fff;
}
section {
width: 100%;
height: 100vh;
}
.middle {
/* needs to be vertically and horizontally aligned */
}
.red-bg {
background-color: #f00;
}
.blue-bg {
background-color: #00f;
}
尝试flexbox
body {
color: #fff;
}
section {
width: 100%;
height: 100vh;
display : flex;
}
.middle {
/* needs to be vertically and horizontally aligned */
margin : auto;
}
.red-bg {
background-color: #f00;
}
.blue-bg {
background-color: #00f;
}
<section class="red-bg">
<div class="middle">
<img src="http://lorempixel.com/g/300/300/abstract/" alt="" />
<h1>Some text here.</h1>
</div>
</section>
<section class="blue-bg">
<p>Another section here.</p>
</section>
试试这个。http://jsfiddle.net/stybfgju/1/
.middle {
/* vertical centering */
position: relative;
top: 50%;
transform: translateY(-50%);
/* horizontal centering */
margin: 0 auto;
display: table;
}
- 如果将
display
更改为block
,则需要显式设置width
- 如果需要,添加
text-align: center