CSS如何实现子元素div水平垂直居中

发布时间:2021-03-17 11:09:17 作者:清风
来源:亿速云 阅读:198

本文将为大家详细介绍“CSS如何实现子元素div水平垂直居中”,内容步骤清晰详细,细节处理妥当,而小编每天都会更新不同的知识点,希望这篇“CSS如何实现子元素div水平垂直居中”能够给你意想不到的收获,请大家跟着小编的思路慢慢深入,具体内容如下,一起去收获新知识吧。

div基本布局

<div class="main">
   <div class="center"></div>
  </div>

css样式

1. 配合定位与margin:auto

父元素加相对定位,子元素加绝对定位

 .main{
    width: 300px;
    height: 300px;
    background-color: red;
    position: relative;
   }
   .center{
    width: 100px;
    height: 100px;
    background-color: skyblue;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
   }

2.利用flex布局,设置水平与竖直方向的内容居中。

 .main{
    width: 300px;
    height: 300px;
    background-color: red;
    display: flex;
    justify-content: center;
    align-items: center;
   }
   .center{
    width: 100px;
    height: 100px;
    background-color: greenyellow;
   }

3.利用position:absolute与transform

:这里需要记住的是transform中translate使用百分比时相对的是自己的长宽,不是父盒子的。

 .main{
     width: 300px;
     height: 300px;
     background-color: red;
     position: relative;
    }
    .center{
     width: 100px;
     height: 100px;
     background-color: pink;
     position: absolute;
     left: 50%;
     top: 50%;
     transform: translateX(-50%) translateY(-50%);
    }

4.定位 与负margin配合

只适合子盒子长宽固定的情况

 .main{
     width: 300px;
     height: 300px;
     background-color: red;
     position: relative;
    }
    .center{
     width: 100px;
     height: 100px;
     background-color: pink;
     position: absolute;
     left: 50%;
     top: 50%;
     margin-left: -50px;
     margin-top: -50px;
    }

5.display:table-cell

display:table-cell;与vertical-align:middle 的作用是让子盒子在数值方向上居中

margin:auto;则让子盒子在水平方向居中,若只想让盒子在某个方向居中,去掉另一个就可以了。

.main{
     width: 300px;
     height: 300px;
     background-color: red;
     display: table-cell;
     vertical-align: middle;
    }
    .center{
     width: 100px;
     height: 100px;
     background-color: #000;
     margin: auto;
    }

如果你能读到这里,小编希望你对“CSS如何实现子元素div水平垂直居中”这一关键问题有了从实践层面最深刻的体会,具体使用情况还需要大家自己动手实践使用过才能领会,如果想阅读更多相关内容的文章,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. css3实现元素水平垂直居中
  2. css div子元素剧中

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

css 子元素

上一篇:css中如何实现收货地址平行四边形的线条样式

下一篇:css子元素相对父元素进行定位的实现方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》