美文网首页
CSS盒子水平垂直居中的四种方式

CSS盒子水平垂直居中的四种方式

作者: 晚月川 | 来源:发表于2020-03-23 20:00 被阅读0次

一个元素在另一个元素水平垂直居中位置 面试题

需要宽高的两种

第一个方法

  • 设置宽高
  • 设置绝对定位
  • 设置left/top为50%
  • margin-left:-宽度/2
  • margin-top:-高度/2
.box {
    position: absolute;
    left:50%;
    top:50%;
    margin-left:-50px;
    margin-top:-50px;
    width:100px;
    height: 100px;
    background-color: red;
}

第二种方法

  • 设置宽高
  • 设置绝对定位属性
  • 设置left/right/top/bottom为0
  • 设置margin:auto
.box {
    position: absolute;
    left:0;
    top:0;
    right:0;
    bottom:0;
    margin:auto;
    width:100px;
    height: 100px;
    background-color: green;
}

不要需要宽高的两种

第一种方法
transforms 变形(最简单的方法)

内容块定义transform: translate(-50%,-50%) 必须加上top: 50%; left: 50%;

.box {
     padding: 20px;
     background: orange;
     color: #fff;
     position: absolute;
     top: 50%;
     left: 50%;
     border-radius: 5px;
     -webkit-transform: translate(-50%, -50%);
     -moz-transform: translate(-50%, -50%);
     transform: translate(-50%, -50%);
}

第二种方法
给父元素加CSS属性

.box{
    justify-content: center; /*子元素水平居中*/
    align-items: center; /*子元素垂直居中*/
    display: -webkit-flex;
}

相关文章

网友评论

      本文标题:CSS盒子水平垂直居中的四种方式

      本文链接:https://www.haomeiwen.com/subject/kgvbyhtx.html