一、元素定宽高
1.absolute + 负margin
PC端有兼容性要求,宽高固定,推荐
<style type="text/css">
.box{
border: 1px solid red;
width: 300px;
height: 300px;
position: relative; //关键代码
}
.box1.size{
width: 100px;
height: 100px;
background: red;
}
.box1 {
position: absolute; //关键代码
top: 50%; //关键代码
left: 50%; //关键代码
margin-left: -50px; //关键代码
margin-top: -50px; //关键代码
}
</style>
<body>
<div class="box">
<div class="box1 size">absolute + 负margin</div>
</div>
</body>
2.absolute + margin:auto
<style type="text/css">
.box{
border: 1px solid red;
width: 300px;
height: 300px;
position: relative; //关键代码
}
.box1.size{
width: 200px;
height: 200px;
background: red;
}
.box1 {
position: absolute; //关键代码
top:0; //关键代码
left: 0; //关键代码
right: 0; //关键代码
bottom: 0; //关键代码
margin:auto; //关键代码
}
</style>
<body>
<div class="box">
<div class="box1 size">absolute + margin:auto</div>
</div>
</body>
3.absolute + calc
<style type="text/css">
.box{
border: 1px solid red;
width: 300px;
height: 300px;
position: relative; //关键代码
}
.box1.size{
width: 100px;
height: 100px;
background: red;
}
.box1 {
position: absolute; //关键代码
top: calc(50% - 50px); //关键代码
left: calc(50% - 50px); //关键代码
}
</style>
<body>
<div class="box">
<div class="box1 size">absolute + calc</div>
</div>
</body>
二、元素不定宽高
1.absolute + transform
<style type="text/css">
.box{
border: 1px solid red;
width: 300px;
height: 300px;
position: relative; //关键代码
}
.box1 {
position: absolute; //关键代码
top: 50%; //关键代码
left: 50%; //关键代码
transform: translate(-50%, -50%); //关键代码
}
</style>
<body>
<div class="box">
<div class="box1">absolute + transform</div>
</div>
</body>
2.lineheight + vertical-align
适用在子元素中将文字显示居中
<style type="text/css">
.box{
border: 1px solid red;
width: 300px;
height: 300px;
line-height: 300px; //关键代码
text-align: center; //关键代码
font-size: 0px; //关键代码
}
.box1 {
font-size: 16px; //关键代码
display: inline-block; //关键代码
vertical-align: middle; //关键代码
line-height: initial; //关键代码
}
</style>
<body>
<div class="box">
<div class="box1">absolute + transform</div>
</div>
</body>
3.flex布局
PC端无兼容性要求,移动端推荐使用
<style type="text/css">
.box{
border: 1px solid red;
width: 300px;
height: 300px;
display: flex; //关键代码
justify-content: center; //关键代码
align-items: center; //关键代码
}
</style>
<body>
<div class="box">
<div class="box1">flex布局</div>
</div>
</body>
4.css-table
PC端有兼容要求,宽高不固定
<style type="text/css">
.box{
border: 1px solid red;
width: 300px;
height: 300px;
display: table-cell; //关键代码
text-align: center; //关键代码
vertical-align: middle; //关键代码
}
.box1{
display: inline-block;
}
</style>
<body>
<div class="box">
<div class="box1">css-table</div>
</div>
</body>