CSS positioning to fill container: width vs. left/right?

前端 未结 4 1683
梦如初夏
梦如初夏 2020-12-16 11:49

Considering:

  • For elements that are absolutely positioned inside a relatively positioned container.
  • If you want the element to fill the width of the co
4条回答
  •  鱼传尺愫
    2020-12-16 12:29

    Historically we learnt to use width instead of left & right because IE6 didn't support at the same time the two properties of the same axis

    modern browsers
    MSIE6
    modern browsers
    MSIE6
    modern browsers
    MSIE6

    Also, this technique will not work on some elements (including on modern browsers, by spec )

    
    
    
    
    
    
    
    
    
    
    
    and possibly others... (some of these can't even be display:block)
    

    But, analysing what happens in the normal static flow using the width:auto property

    a

    You will see it's very similar to...

    b

    ... same properties with the same values! This is really nice! Otherwise it will look like:

    c

    Which is also different, because the inner div doesn't fill the y axis. To fix this we will need css calc() or box-sizing and an unnecessary headache.


    My answer is, left + right | top + bottom are really cool since they are closest to the static positioning's width:auto and there is no reason to not use them. They are way easier to use compared to the alternative and they provide much more functionality (for example, using margin-left, padding-left and left at the same time in one single element).

    left + right | top + bottom is considerably better supported by browsers compared to the alternative width:100% + box-sizing | calc() and it's also easier to use!

    Of course if you don't need (as in your example) to grow the element also in the y axis, width:100% using some nested element for the padding, it's the only solution to archive support also for MSIE6

    So, depends by your needs. If you want to support MSIE6 (it's the only actual reason to do that) you should use with:100%, otherwise use left + right!

    Hoping to be helpful.

提交回复
热议问题