欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

css实现div水平/垂直居中的N中方法

程序员文章站 2022-04-24 22:19:08
...

1、父div内部的所有子div水平居中

// html 代码
<div class="parent">
    <div class="chil"></div>
    <div class="chil"></div>
    <div class="chil"></div>
</div>

/*子元素纵向排列水平居中*/
// css 代码
.parent{
    width: 400px; 
    height: 600px; 
} 
.chil{ 
    width: 120px;
    height: 120px; 
    margin: 0 auto; 
}

/*子元素横向排列且水平居中*/
//css代码
.parent{
    width: 400px;
    height: 400px;
    text-align: center;

}
.chil{
    width: 120px;    
    height: 120px;
    display: inline-block;
}

/*子元素纵向排列垂直居中*/
//css 代码
.parent{
    width: 400px; 
    height: 600px; 
    display: table-cell; 
    vertical-align: middle; 
} 
.chil{ 
    width: 30%; 
    height: 30%; 
}

/*子元素横向排列垂直居中*/
// cs 代码
.parent{
    width: 400px; 
    height: 400px; 
    display: flex; 
    align-items:center; 
} 
.chil{ 
    width: 30%; 
    height: 30%; 
}

/*子元素水平方向垂直方向都居中 方式一*/
//css代码
.parent{
    width: 400px; 
    height: 400px; 
    display: table-cell; 
    vertical-align: middle; 
    text-align: center; 
} 
.chil{ 
    width: 30%; 
    height: 30%; 
    display: inline-block; 
}

/*子元素水平方向垂直方向都居中 方式二 如果有多个子元素会重叠在父元素中心位置*/
//css代码
.parent{
    width: 400px; 
    height: 400px; 
    position: relative; 
} 
.chil{ 
    width: 30%; 
    height: 30%; 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    transform:translate(-50%, -50%);
    //transform:translate(0, -50%); 垂直方向上居中且多个子元素重叠
    //transform:translate(-50%); 水平方向上居中且多个子元素重叠
}