css设置子元素在父元素中水平垂直居中
1. 第一种方式:使用Flexbox布局
- 设置父元素的样式为以下样式,即可实现元素水平垂直居中。
.container { display: flex; justify-content: center; align-items: center; }
2. 第二种方式:使用绝对定位
- 父元素设置
position: relative
,子元素设置绝对定位,子元素相对父元素定位,子元素设置top: 50%; left: 50%
,相对父元素向下向右偏移父元素的50%
。子元素再transform: translate(-50%, -50%)
,相对子元素自身向左向上偏移50%
,这样子元素就位于父元素的中间,水平垂直居中。.container { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
3. 第三种方式:使用表格布局
- 将父元素的样式设置为
display: table
;,然后将子元素设置为display: table-cell; vertical-align: middle; text-align: center;
即可实现水平垂直居中。.container { display: table; } .centered-element { display: table-cell; vertical-align: middle; text-align: center; }
4. 第四种方式:使用绝对定位和负边距
- 父元素设置
position: relative
,将子元素的position
属性设置为absolute
,并同时设置top、left、bottom、right
属性的值都为0
,并使用负边距(margin
)将元素向外扩展一定的宽度和高度。.container { position: relative; } .centered-element { position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; }