怎么让一个不定宽高的div水平居中,垂直水平居中?

一开始,我看到这个问题的时候,心里想这么简单,不就是margin:0 auto吗,再仔细看题目的时候,我去,不定宽高,什么鬼,于是,只能自己动手,亲手实验了。


1、利用弹性布局,这是我认为最简单的且容易理解的方法

html:

<body>
<div class="one">
<div class="two">wo</div>
<div class="three">shi</div>
<div class="four">xian</div>
<div class="five">yu</div>
</div>
</body>


css:

<style>
    
        .one {
width: 500px;
height: 500px;
background-color: royalblue;
display: flex; //弹性布局
justify-content: space-around; //水平居中
align-items: center; //垂直居中
}
.one>div {
background-color: yellowgreen;
}
</style>


效果:

怎么让一个不定宽高的div水平居中,垂直水平居中?

2、利用css3和定位的方法

html:

<body>
<div class="one">
<div class="two">wo</div>
</div>
</body>


css:

<style>
    
    .one {
position: relative;
width: 200px;
height: 200px;
background-color: rebeccapurple;
}

.two {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>

效果:

怎么让一个不定宽高的div水平居中,垂直水平居中?

3,利用css

html :

<body>
<div class="one">
<div class="two">wo</div>
</div>
</body>


css:

<style>
    
        .one {
display: table-cell;
text-align: center;
vertical-align: middle;
width: 100px;
height: 100px;
background-color: red;
}

.two {
vertical-align: middle;
display: inline-block;
}
</style>


效果:

怎么让一个不定宽高的div水平居中,垂直水平居中?


注意点:一定要在子盒子里面添加内容,因为子盒子的div本身是没有宽高的,如果你不加内容,根本无法实现效果