CSS中如何让div居中显示呢?以下是几种方法:
1.使用margin属性
<style>
div {
width: 200px;
height: 100px;
background-color: red;
margin: auto;
}
</style>
<div></div> 使用margin属性设置上下左右的值都为自动,即可让div在其父元素中水平和垂直居中显示。
2.使用flex布局
<style>
.container {
display: flex;
justify-content: center; /*水平居中*/
align-items: center; /*垂直居中*/
height: 100vh;
}
.item {
width: 200px;
height: 100px;
background-color: red;
}
</style>
<div class="container">
<div class="item"></div>
</div> 使用flex布局,将父元素的display属性设置为flex,同时设置justify-content和align-items属性,即可实现div的水平和垂直居中。
3.使用absolute布局
<style>
.container {
position: relative;
height: 100vh;
}
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
background-color: red;
}
</style>
<div class="container">
<div class="item"></div>
</div> 使用absolute布局,设置父元素的position属性为relative,设置div的position属性为absolute,同时设置top、left和transform属性,即可实现div的水平和垂直居中。