【CSS】居中元素定宽高,居中元素不定宽高
目录
居中元素定宽高
abosolute + 负 margin
元素偏移后,再修正元素自身宽高的一半,及可实现剧中显
CSS
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
position: relative;
}
.box {
background: green;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
.box .fixed-size {
width: 100px;
height: 100px;
}
HTML
<div class="wp">
<div class="box fixed-size">text </div>
</div>
absolute + calc
CSS
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
position: relative;
}
.box {
background: green;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
.box .fixed-size {
width: 100px;
height: 100px;
}
居中元素不定宽高
absolute + transform
CSS
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
position: relative;
}
.box {
background: green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
HTML
<div class="wp">
<div class="box">text </div>
</div>
line height
CSS
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
line-height: 300px;
text-align: center;
font-size: 0;
}
.box {
background: green;
font-size: 16px;
display: inline-block;
vertical-align: middle;
line-height: initial;
text-align: left;
}
CSS table
CSS
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box {
background: green;
display: inline-block;
}
flex
CSS
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.box {
background: green;
}
grid
CSS
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
display: grid;
}
.box {
background: green;
align-self: center;
justify-self: center;
}

浙公网安备 33010602011771号