margin-left: auto;为什么可以使元素靠右

div {
  width: 100px;
  margin-left: auto;
}

上面的代码可以使得div靠近浏览器的右侧显示是为什么?

有点弱智的问题,竟然现在才知道...记录一下 

The following constraints must hold among the used values of the other properties:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' +'border-right-width' + 'margin-right' = width of containing block

你的属于其中一种情况:
If there is exactly one value specified as 'auto', its used value follows from the equality.

也就是在上述等式中,只有你设置的margin-left: auto,那么margin-left将会被设置为满足上述等式,而等式的右边是容器盒子宽度,等式中的其它值(除过width)都为0,因此margin-left = width of containing block - width(div)

再来看一下我们经常使用的 margin: auto 水平居中的原理。

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

转自知否  https://segmentfault.com/q/1010000008431088

  • 8
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值