关于margin:auto, margin-left:auto

350 阅读1分钟

w3c 规定: 常规流中的块级非浮动元素需要满足: 'margin-left' + 'border-left-width' + padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = 包含块的宽度

若恰好只有一个值被指定为 'auto',则该使用值由上面的等式求出

CSS2/visudet - HTML5 Chinese Interest Group Wiki (w3.org)

实际运用中可以记住如下两个规则:

  • 常规流中的块级非浮动元素, 如果一侧定值,一侧auto,则auto为剩余空间大小
  • 常规流中的块级非浮动元素, 如果两侧均是auto,则平分剩余空间

上面的规定在实际应用中有哪些体现?

  1. 如我们常使用的让元素水平居中的方式: margin:auto
  2. 使用该特性实现类似左右浮动的效果
  3. 结合flex布局, 实现分组布局的效果

第一点好理解, 主要说下第二点和第三点

实现类似右浮动效果

<template>
  <div class='container'>
    <div>1</div>
  </div>
</template>

<script lang='ts' setup>
</script>

<style lang='scss' scoped>
.container {
  height: 300px;
  background-color: lightblue;

  div {
    box-sizing: border-box;
    width: 100px;
    height: 90px;
    background-color: lightgoldenrodyellow;
    border:1px solid #333;
  }

  div:nth-of-type(1){
    // >>>>>>>>>>>>>>>>>>>> 注意这里
    margin-left: auto;
  }
}
</style>

image.png

结合flex实现分组布局的代码和效果

先看下如下flex布局效果

<template>
  <div class='container'>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
  </div>
</template>

<script lang='ts' setup>
</script>

<style lang='scss' scoped>
.container {
  display: flex;
  flex-direction: row;
  height: 300px;
  background-color: lightblue;

  div {
    box-sizing: border-box;
    width: 100px;
    height: 90px;
    background-color: lightgoldenrodyellow;
    border:1px solid #333;
  }
}
</style>

image.png

<template>
  <div class='container'>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
  </div>
</template>

<script lang='ts' setup>
</script>

<style lang='scss' scoped>
.container {
  display: flex;
  flex-direction: row;
  height: 300px;
  background-color: lightblue;

  div {
    box-sizing: border-box;
    width: 100px;
    height: 90px;
    background-color: lightgoldenrodyellow;
    border:1px solid #333;
  }

  div:nth-of-type(2){
    // >>>>>>>>>>>>>>>>>>>> 注意这里
    margin-left: auto;
  }

  div:nth-of-type(4){
    // >>>>>>>>>>>>>>>>>>>> 注意这里
    margin-left: auto;
  }
}
</style>

这里就被分成了3组, 第一组: 1 第二组: 2,3 第三组: 4

image.png

结合上面的效果, 然后再看上面w3c的规定, 你品, 你细品. 记住有这个特性, 会利用这个特性即可.