目录
三:将内部盒子转化为行内块元素使用vertical-align
垂直水平居中单挑出来就可以做水平或者垂直居中
默认结构和样式
<div class="parentDiv">
<div class="childDiv"> 子盒子 </div>
</div>
.parentDiv{
width: 300px;height: 300px;border: 5px salmon solid;
position: relative;
}
.childDiv{width: 100px; height: 100px;background: violet;}
一:子元素属性添加
①使用定位 和 外边距
1>(position:absolute;margin:-selfWidth -selfHeight)
position: absolute;/*或者relative*/
top: 50%;left: 50%;
margin: -50px -50px;
2>(position:absolute;top right bottom left:0;margin:auto)
position: absolute;
top: 0;right: 0;bottom: 0;left: 0;
margin: auto;
②使用 定位 + calc动态计算
position: absolute;/*或者relative*/
top: calc(50% - 50px);
left:calc(50% - 50px); ;
③使用 定位 + transform
position: absolute;/*或者relative*/
top: 50%;left: 50%;
transform: translateX(-50%) translateY(-50%);
二:父元素属性添加---使用弹性盒子
display:flex;
justify-content: center; /*justify-content水平布局*/
align-items: center; /* align-item 垂直布局*/
三:将内部盒子转化为行内块元素使用vertical-align
.parentDiv{
width: 300px;height: 300px; border: 5px salmon solid;
text-align: center;
line-height: 300px;
}
.childDiv{
width: 100px; height: 100px;background: violet;
display: inline-block;
vertical-align: middle;
line-height: 1;
}
vertical-align用来定义行内元素的基线相对于该元素所在行的基线的垂直对齐
middle属性指将支持valign特性的对象的内容与对象中部对齐