在前端开发时,经常会遇到需要居中的情形,居中分2种情况,一个是水平居中,一个是垂直居中,总结一下用到的方法。
水平居中实现
margin:0 auto
auto表示外边距左右距离相同即可实现水平居中的效果
垂直居中实现
1、最常用到的一种方式是根据偏移量来实现
<style>
*{margin: 0;padding: 0;}
.content{
position: relative;
width: 300px;
height: 300px;
background-color: #000;
margin: 300px auto;
}
.beat{
width: 100px;
height: 100px;
background-color: #ff0000;
position: absolute;
left:50%;
top:50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
<div class="content">
<div class="beat">
</div>
</div>
红色方块位于黑色方块的中心位置,实现了垂直居中效果
left,top分别设置50%,红色方块的起始点位于垂直居中的位置,效果如下图:
想要实现方块内部中心点垂直居中,还要加上偏移量,margin-top的值为红色框heigh/2,margin-left的值为红色框width/2。
2、让div块里的多行文字垂直居中,可以用table和table-cell来实现
<style>
*{margin: 0;padding: 0;}
.content{
width: 300px;
height: 300px;
background-color: #000;
margin: 300px auto;
color: #fff;
display: table;
text-align: center;
}
.content p{
display: table-cell;
height: 100px;
vertical-align: middle;
}
</style>
<div class="content">
<p>垂直居中是布局中十分常见的效果之一垂直居中是布局中十分常见的效果之一垂直居中是布局中十分
常见的效果之一垂直居中是布局中十分常见的效果之一</p>
</div>
display: table使块状元素成为一个块级表格,display: table-cell;子元素设置成表格单元格,vertical-align: middle;使表格内容居中显示,即可实现垂直居中的效果
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。