我试图将两个 <p>
垂直居中元素。
我遵循了 phrogz.net 上的教程但元素仍然放置在 div 上方,div 下方,在 div 内顶部对齐。
我会尝试其他方法,但这里的大多数问题都指向那个教程。
此代码段用于网页顶部的横幅。
.banner {
width: 980px;
height: 69px;
background-image: url(../images/nav-bg.jpg);
background-repeat: no-repeat;
/* color: #ffffff; */
}
.bannerleft {
float: left;
width: 420px;
text-align: right;
height: 652px;
line-height: 52px;
font-size: 28px;
padding-right: 5px;
}
.bannerright {
float: right;
width: 555px;
text-align: left;
position: relative;
}
.bannerrightinner {
position: absolute;
top: 50%;
height: 52px;
margin-top: -26px;
}
<div class="banner">
<div class="bannerleft">
I am vertically centered
</div>
<div class="bannerright">
<div class="bannerrightinner">
<p>I should be</p>
<p>vertically centered</p>
</div>
</div>
<div class="clear">
</div>
</div>
如何使元素垂直、水平或两者居中
这里有两种在 div 中居中 div 的方法。
一种方法使用 CSS Flexbox 另一种方式使用 CSS table 和 positioning 属性。
在这两种情况下,居中的 div 的高度可以是可变的、未定义的、未知的,等等。居中的 div 的高度无关紧要。
这是两者的 HTML:
<div id="container">
<div class="box" id="bluebox">
<p>DIV #1</p>
</div>
<div class="box" id="redbox">
<p>DIV #2</p>
</div>
</div>
CSS Flexbox 方法
#container {
display: flex; /* establish flex container */
flex-direction: column; /* stack flex items vertically */
justify-content: center; /* center items vertically, in this case */
align-items: center; /* center items horizontally, in this case */
height: 300px;
border: 1px solid black;
}
.box {
width: 300px;
margin: 5px;
text-align: center;
}
DEMO
两个子元素 (.box
) 与 flex-direction: column
垂直对齐。对于水平对齐,将 flex-direction
切换为 row
(或者简单地删除规则,因为 flex-direction: row
是默认设置)。这些元素将保持垂直和水平居中 ( DEMO )。
CSS表格和定位方法
body {
display: table;
position: absolute;
height: 100%;
width: 100%;
}
#container {
display: table-cell;
vertical-align: middle;
}
.box {
width: 300px;
padding: 5px;
margin: 7px auto;
text-align: center;
}
DEMO
使用哪种方法...
如果您不确定使用哪种方法,我会推荐 flexbox,原因如下:
- 最少的代码;非常有效率
- 如上所述,居中简单易行 ( see another example )
- equal height columns are simple and easy
- multiple options for aligning flex elements
- react 灵敏
- 与 float 和表格不同,它们提供有限的布局能力,因为它们从未用于建筑布局,而 flexbox 是一种具有广泛选项的现代 (CSS3) 技术。
浏览器支持
所有主流浏览器都支持 Flexbox,except IE < 10 .一些最新的浏览器版本,例如 Safari 8 和 IE10,需要 vendor prefixes .要快速添加前缀,请使用 Autoprefixer .更多详细信息,请参阅 this answer .