css实现垂直水平居中的5种方法
- 给父元素设置table-cell,text-align,vertical-align
#big{
width: 200px;
height: 200px;
border:1px solid #000;
display: table-cell;
text-align: center;
vertical-align: middle;
}
#small{
display: inline-block;
width: 50px;
height: 50px;
background: yellow;
vertical-align:middle;
}
- 给子元素设置margin:auto
#big{
width: 200px;
height: 200px;
border:1px solid #000;
position: relative;
}
#small{
display: inline-block;
width: 50px;
height: 50px;
background: yellow;
position: absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
}
- 弹性盒
#big{
width: 200px;
height: 200px;
border:1px solid #000;
display: flex;
align-items: center;
justify-content: center;
}
#small{
display: inline-block;
width: 50px;
height: 50px;
background: yellow;
}
- 利用translate实现,先进行绝对定位,然后通过translate让它自身往回移动50%
#big{
width: 200px;
height: 200px;
border:1px solid #000;
position: relative;
}
#small{
display: inline-block;
width: 50px;
height: 50px;
background: yellow;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
- 通过新创建一个元素,设置高为父元素的高,让div以这个元素来执行vertical-align
#big{
width: 200px;
height: 200px;
border:1px solid #000;
text-align: center;
}
#small{
display: inline-block;
width: 50px;
height: 50px;
background: yellow;
vertical-align: middle;
}
span{
display: inline-block;
width: 0;
height: 100%;
background: red;
vertical-align: middle;
}
</style>
</head>
<body>
<div id="big">
<div id="small">
</div>
<span></span>
</div>
</body>
时间: 2024-10-26 11:11:02