实现盒模型水平居中的方法
全局样式
.parent {
color: #FFFFFF;
height: 200px;
width: 200px;
margin: 0 auto;
background-color: #000000;
}
.child {
width: 50px;
height: 50px;
background-color: #26f12d; }
方法一:margin+width
这种方法适用于已经知道width的盒子
<div class="parent">
<div class="child"></div>
</div>
.child {
width: 50px;
margin: 0 auto;
}
方法二:text-align+inline-block
<div class="parent">
<div class="child"></div>
</div>
.parent {
text-align: center;
}
.child {
display: inline-block;
}
方法三:float+position
<div class="parent">
<div class="between">
<div class="child"></div>
</div>
</div>
.between {
position: relative;
left: 50%;
float: left;
}
.child {
position: relative;
right: 50%;
}
方法四:
<div class="parent">
<div class="between">
<div class="child"></div>
</div>
</div>
.parent {
position: relative;
}
.between {
position: absolute;
left: 50%;
}
.child {
position: relative;
right: 50%;
}
方法五:flex
<div class="parent">
<div class="child"></div>
</div>
.parent {
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-orient: horizontal;
}
方法六:fit-content
<div class="parent">
<div class="between">
<div class="child"></div>
</div>
</div>
.between {
width: -webkit-fit-content;
margin: 0 auto;
}
实现盒子模型垂直居中的方法
方法一:position
这种方法适用于已经知道width的盒子
<div class="parent">
<div class="child"></div>
</div>
.parent {
position: relative;
width: 200px;
height: 200px;
}
.child {
position: absolute;
margin: 75px 0;
}
方法二:position+transform
这种方法适用于已经知道width的盒子
<div class="parent">
<div class="child"></div>
</div>
.parent {
position: relative;
width: 200px;
height: 200px;
}
.child {
position: absolute;
top: 50%;
transform: translate(0%, -50%);
}
方法三:flex布局
<div class="parent">
<div class="child"></div>
</div>
.parent {
display: flex;
align-items: center;
}
方法四:table-cell布局
<div class="parent">
<div class="between">
<div class="child"></div>
</div>
</div>
.parent {
display: table;
}
.between {
display: table-cell;
vertical-align: middle;
}
实现盒子模型水平垂直居中方法
方法一:
<div class="parent">
<div class="child"></div>
</div>
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
方法二:
<div class="parent">
<div class="child"></div>
</div>
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
方法三:
<div class="parent">
<div class="child"></div>
</div>
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px; /* 自身 height 的一半 */ margin-left: -25px; /* 自身 width 的一半 */
}
网友评论