举例:
<div class="parent">
<p class="son">
会议认为,党的十八大以来,我国经济发展取得历史性成就、 发生历史性变革,为其他领域改革发
展提供了重要物质条件。经济实力 再上新台阶,经济年均增长7.1%,成为世界经济增长的主要动力
源和稳定器。
</p>
</div>
方法一:给父元素display:table ;text-align:center;子元素:diasplay:table-cell;vertical-align:center;
.parent {
display: table;
width: 300px;
height: 300px;
margin: auto;
background-color: pink;
/* 父元素的背景颜色设置无效 */
}
.son {
display: table-cell;
/* height:200px 高度设置无效 默认父元素的高度 */
background-color: skyblue;
vertical-align: middle;
border: 1px solid red;
}
效果图:

方法二:给父元素相对定位,给子元素绝对定位top: 50%; left: 50%;transform: translate(-50%, -50%);
.parent {
position: relative;
width: 300px;
height: 300px;
margin: auto;
background-color: pink;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 200px;
width: 200px;
background-color: skyblue;
border: 1px solid red;
}
CSS居中布局技巧
本文介绍了两种使用CSS实现元素在父容器中水平垂直居中的方法:一是通过设置父元素display:table及子元素display:table-cell;二是利用相对定位与绝对定位结合transform属性。
1615

被折叠的 条评论
为什么被折叠?



