CSS:不同元素margin:auto的计算

关于什么元素的分类可以看我这篇文章CSS:关于元素高度与宽度的讨论 系列文章(二)

行内级元素

  • Inline,非置换元素:如果margin值为auto,则margin-leftmargin-right的计算值也就为0

  • Inline,置换元素:同上

  • Inline-block,置换元素在文档流中:同上

  • Inline-block,非置换元素在文档流中:同上

块级元素

块级非置换元素,在文档流中

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

下面的情况下,如果margin值为auto

  • 如果width是auto值,那么其他值是auto的值就为0

  • 如果margin-leftmargin-right的值为auto,width的值不为auto,那么就相对于包含块水平居中。

块级置换元素,在文档流中

同块级非置换元素一样。

块级非置换元素,不在文档流中(Absolutely positioned, non-replaced elements)

// 当top/height/bottom 这3个值不是auto,而 margin:auto ,则:
margin-top=margin-bottom=(包含块的高度 – 定位元素高度)/2
'top' + 'margin-top' + 'border-top-width' + 'padding-top' + 'height' + 'padding-bottom' + 'border-bottom-width' + 'margin-bottom' + 'bottom' = height of containing block
    <style>
    #parent {
        background: #999;
        height: 300px;
        position: relative;
        width: 300px;
    }
    #child {
        background: #333;
        height: 50px;
        bottom: 0;
        top: 0;
        left: 0;
        right: 0;
        margin: auto;
        position: absolute;
        width: 50px;
    }
    </style>
    
    <div>
        <div id="parent">
        <div id="child"></div>
    </div>

clipboard.png

块级置换元素,不在文档流中

同上

总结

行内级元素

行内级置换元素和非置换元素,在margin值为auto时,margin-leftmargin-auto的计算值都为0。

块级元素

  1. 块级置换元素和非置换元素在文档流中:

    'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block 
    
  • 如果width是auto值,那么其他值是auto的值就为0

  • 如果margin-leftmargin-right的值为auto,width的值不为auto,那么就相对于包含块水平居中。

2.块级置换元素和非置换元素不在文档流中。
见上文。

The percentage is calculated with respect to the width of the generated box’s containing block. Note that this is true for margin-top and margin-bottom as well.

abs-non-replaced-height
Why does “position: absolute; left: 0; right: 0; width: XYpx; margin: 0 auto” actually center?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值