如何让不定宽高的盒子居中

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>

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>

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本身是没有宽高的,如果你不加内容,根本无法实现效果

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容