考虑:

  • 用于绝对定位在相对内部的元素
    定位的容器。
  • 如果要让元素填充容器的宽度。
  • 元素也向下对齐。


  • 最好是最大程度地实现元素与set a width in pixelsuse left and right 的最大浏览器兼容性?

    任何一种方法都需要注意的常见错误?

    显然,在更改图像的宽度或填充的情况下,使用left: 0;right: 0;将使代码更易于管理,但是还有其他不利于width: 300px的缺点吗?

    最佳答案

    历史上我们学会了使用width而不是left & right,因为IE6不支持
    同时同一轴的两个属性

    <div style="top:0;bottom:0;position:absolute;">modern browsers</div>
    
    <div style="top:0;height:100%;position:absolute;">MSIE6</div>
    
    <div style="left:0;right:0;position:absolute;">modern browsers</div>
    
    <div style="left:0;width:100%;position:absolute;">MSIE6</div>
    
    <div style="left:0;right:0;top:0;bottom:0;position:absolute;">modern browsers</div>
    
    <div style="left:0;top:0;height:100%;width:100%;position:absolute;">MSIE6</div>
    

    另外,此技术不适用于某些元素(including on modern browsers, by spec)
    <!-- these will not work -->
    <!-- edit: on some browsers they may work,
    but it's not standard, so don't rely on this -->
    
    <iframe src="" style="position:absolute;top:0;bottom:0;left:0;right:0;"></iframe>
    
    <textarea style="position:absolute;top:0;bottom:0;left:0;right:0;"></textarea>
    
    <input type="text" style="position:absolute;left:0;right:0;">
    
    <button ... ></button>
    
    and possibly others... (some of these can't even be display:block)
    

    但是,使用width:auto属性分析正常静态流中发生的情况
    <div style="width:auto;padding:20px;margin:20px;background:lime;">a</div>
    

    您会看到它与...非常相似
    <div style="width:auto;padding:20px;margin:20px;background:lime;
        position:absolute;top:0;left:0;bottom:0;right:0;">b</div>
    

    ...具有相同值的相同属性!真是太好了!否则它将看起来像:
    <div style="width:100%;height:100%;
        position:absolute;top:0;left:0;">
        <div style="padding:20px;margin:20px;
            background:lime;">c</div>
    </div>
    

    这也有所不同,因为内部div不会填充y轴。
    要解决此问题,我们将需要CSS的calc()box-sizing和不必要的麻烦。

    我的答案是,left + right | top + bottom真的很酷,因为它们最接近静态定位的width:auto而且没有理由不使用它们。与替代方法相比,它们更易于使用,而且
    提供更多功能(例如,在以下位置同时使用margin-leftpadding-leftleft一个元素)。
    left + right | top + bottom相当大
    与替代的width:100% + box-sizing | calc()相比,浏览器更好地支持了它
    而且更容易使用!

    当然,如果您不需要(例如您的范例)也在y轴上增加元素,width:100%使用一些嵌套元素进行填充,这是唯一也支持MSIE6归档的解决方案

    因此,取决于您的需求。如果要支持MSIE6(这是这样做的唯一实际原因),则应使用with:100%,否则请使用left + right!

    希望对您有所帮助。

    07-24 09:46
    查看更多