前军教程网

中小站长与DIV+CSS网页布局开发技术人员的首选CSS学习平台

how to center a div,如何让一个DIV居中——示例详解

前言

如何让一个DIV居中,这应该是一个简单的问题吧?

难道有很多不同的应用场景,以及不同的写法吗?


常见代码示例

1、采用 margin 水平居中。

在元素的 宽度已知 的情况下,并且 小于父容器的宽度 时,能很直观的看到它居中了。

// 普通左右居中 margin: 0 auto;
.layour-center { margin-left: auto; margin-right: auto; }

2、采用 text-align:center 加 display:inline-block 实现水平居中。

<style type="text/css">
  .parent {
    background-color: coral;
    height: 200px;
    padding-top:15px;

    text-align: center;;
  }
.child {
  background-color: white;
  width:100px;
  height: 50px;

  display: inline-block;
  /* text-align:left;*/ /* 重置为默认 */
}
</style>



3、采用 绝对定位 方式,实现 水平和垂直居中 。一般常见于登录框、弹窗等应用场景。

使用 absolute 属性时,元素的定位是相对于其最近的被定位(position 属性设置为非 static 的元素)的父级元素或祖先元素进行计算的。如果没有找到被定位的父级元素或祖先元素,那么相对于文档的 body 元素进行计算。

使用 fixed 属性时,元素的定位是相对于浏览器窗口的。

所以应该根据实际情况选择具体的属性。

<style type="text/css">
  .container-login {
    background-color: coral;

    position: absolute;
    /* position:fixed */
    /** 
           水平居中
           左边距离50%,同时
           减去自身的 宽度 的一半。
        */
    width:130px;
    left:50%;
    margin-left:-65px; 

    /** 
           垂直居中
           上边距离50%,同时
           减去自身的 高度 的一半。
        */
    height:140px;
    top: 50%;
    margin-top:-70px;

  }
</style>

4、采用 flex 布局,实现 水平和垂直居中 。父容器设置轴线以实现子容器的居中。

<style type="text/css">
  .parent {
    background-color: coral;
    display: flex;
    /* 沿着主轴水平居中 */
    justify-content: center; 
    /* 沿着交叉轴垂直居中 */
    align-items: center; 
    /* 父容器的高度不能为auto */
    height: 300px; 
  }
.child {
  background-color: white;
  /* 确定子元素的大小 */
  width: 200px;
  height: 100px;
}
</style>

5、使用 transform ,实现 水平和垂直居中 。 -50% 表示向左/上移动元素的一半,从而实现完美居中。

<style type="text/css">
  .parent {
    background-color: coral;
    position: relative;
    height: 230px;
  }
.child {
  background-color: white;
  position: absolute;
  width:80px;
  height: 80px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>


人人为我,我为人人,谢谢您的浏览,我们一起加油吧。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言