Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

margin-left: auto元素右对齐以及margin: 0 auto水平居中的原理 #74

Open
TieMuZhen opened this issue Dec 22, 2021 · 0 comments
Labels

Comments

@TieMuZhen
Copy link
Owner

TieMuZhen commented Dec 22, 2021

一、margin-left: auto;元素右对齐

要实现上述右对齐的方式有很多,比如:

  1. flex设置justify-content: flex-end
  2. absolute定位设置rigth: 0
  3. float: right
  4. 当父节点和子节点宽度固定时,设置margin-left: auto

前面三个方法的都好理解,第四个方法相信会让不少人困惑,但它确确实实可以实现,示例如下:

<html>
<head>
  <style>
    .right {
      margin-left: auto;
      width: 100px;
      height: 50px;
      background-color: #f00;
    }
    .box {
      width: 400px;
      border: 1px solid #000
    }
  </style>
</head>
<body>
  <div class="box">
    <div class="right"></div>
  </div>
</body>
</html>

二、margin: 0 auto;水平居中

要实现上述水平居中的方式有很多,其中有一种方式就是在固定宽度时,使用margin: 0 auto可以实现水平居中,想必使用这个方法的时候也会困扰一会。

<html>
<head>
  <style>
    .middle {
      margin: 0 auto;
      width: 100px;
      height: 50px;
      background-color: #0f0;
    }
    .box {
      width: 400px;
      border: 1px solid #000
    }
  </style>
</head>
<body>
  <div class="box">
    <div class="middle"></div>
  </div>
</body>
</html>

三、原理

块级元素中auto属性的计算特性

  • 节点元素满足等式:'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block,除width以外,等号左侧属性的默认值为0。
  • 当且仅当其中某一个属性为auto(计算属性)时,这个auto值就是令等式成立的值。
  • 最后一条,当margin-leftmargin-right都为auto时,两者就会一样,从而使元素居中

参考文献

@TieMuZhen TieMuZhen added the CSS label Dec 22, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant