2.CSS 设置居中的4种方法

亮闪闪的效果图


居中效果图

如何垂直居中一个属性为item的div元素?

<div class="box">
        <div class="item"></div>
</div>

1、方法一

已知子元素宽高,父元素随意;

设置父元素:定位为relative;

设置子元素:
定位为absolute,
left为50%,top为50%,
margin-left为负的子元素宽度的一半,
margin-top为负的子元素高度的一半;

.box {
        position: relative;   
        width: 500px;
        height: 500px;
        background-color: yellow;
    }
.item {
        position: absolute; 
        width: 100px;
        height: 100px;
        left: 50%;    
        top: 50%;   
        background-color: blue;
        margin-left: -50px;    
        margin-top: -50px;  
    }

2、方法二

已知父元素宽高及子元素宽高;

设置父元素:
定位为relative,
margin为auto;

设置子元素:
定位为absolute,
margin-left为(父元素宽 - 子元素宽)/ 2,
margin-top为(父元素高 - 子元素高)/ 2;

.box {
        position: relative;  
        width: 500px;
        height: 500px;
        background-color: yellow;
        margin: auto;   
    }

.item {
        position: absolute;   
        margin-left: 200px;   
                margin-top: 200px;   
        width: 100px;
        height: 100px;
        background-color: blue;
    }

3、方法三

设置父元素:
display为table-cell,
垂直对齐方式vertical-align: middle,
文本水平对齐方式text-align: center;

设置子元素:为块级元素均匀分布display: inline-block;

.box {
        display: table-cell; 
        vertical-align: middle;    
        text-align: center;  
        width: 500px;
        height: 500px;
        background-color: yellow;
    }
.item {
        display: inline-block;  
        width: 100px;
        height: 100px;
        background-color: blue;
    }

4、方法四

设置父元素:
display为flex,
水平居中justify-content: center,
垂直居中align-items:center;

.box {
        display: flex;  
        justify-content: center;  
        align-items:center;  
        width: 500px;
        height: 500px;
        background-color: yellow;
    }
.item {
        width: 100px;
        height: 100px;
        background-color: blue;
    }   
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。