margin: auto的浅理解

2022-06-08  本文已影响0人  晨曦的杂货铺

margin: auto; 你真的理解么? 让我们先看如下案例

<html>
<head>
    <title>Document</title>
    <style>
        #box {
            width: 300px;
            display: flex;
            border: 1px solid paleturquoise;
            justify-content: flex-end;
        }
        .one {
            background: red;
            width: 30px;
            height: 30px;
            margin-right: auto;
        }
        .two {
            background:blue;
            width: 30px;
            height: 30px;

        }
        .three {
            background: green;
            width: 30px;
            height: 30px;

        }
    </style>
</head>
<body>
    <div id="box">
        <div class="one"></div>
        <div class="two"></div>
        <div class="three"></div>
    </div>
</body>
</html>

2.png

解释:

通过flex布局的justify-content: flex-end; 我们可以将所有项移动到右侧。然后通过给第一个元素设置margin-right: auto;可以得到如下效果。 在我们工作中最常用的就是margin: auto; 让块元素水平居中,那么刚刚的margin-right: auto; 怎么就占满了整个空间呢?

下面我们来看一下margin的填充规则:

如果一侧定值,一侧auto,则auto为剩余空间大小 如果两侧均是auto,则平分剩余空间 当我将第一元素上的margin-right: auto; 设置成 margin: auto; 时, 则效果如下:

3.png

再来举一个例子:

 .father {
     width: 300px;
      background-color: #f0f3f9; 
        }
 .son {
     width: 200px;
      height: 120px;
      margin-right: 80px;
      margin-left: auto;
      background-color: #cd0000;
        }

左边距是20px,右边距是80px,这里son的宽度为200px,father的宽度为300px,其中margin-right使用了80px,那么 margin-left: auto;就是计算剩余的值为20px。

6.png

margin-left:anto代替float:right实现右对齐:

将上面的代码中的

 margin-right: 80px;
 margin-left: auto;

改成

 margin-left: auto;
5.png

magin:atuo配合绝对定位实现水平和垂直方向居中:

   .father {
      width: 300px;
      height: 150px;
      background-color: #f0f3f9;
      position: relative;
    }

    .son {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      width: 200px;
      height: 100px;
      background-color: #cd0000;
      margin: auto;
    }
4.png
上一篇 下一篇

猜你喜欢

热点阅读