CSS定位填充容器:宽度与左/右?

Bau*_*umr 18 css cross-browser css-position width

考虑到:

  • 对于绝对位于相对定位的容器内的元素.
  • 如果希望元素填充容器的宽度.
  • 该元素也是底部对齐的.

在此输入图像描述

最大化浏览器兼容性是否最好为元素设置width像素,或者只使用leftright

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

显然,使用left: 0;right: 0;会使代码在图像的宽度或填充要改变的情况下更容易管理,但没有任何缺点,其中width: 300px将有利于呢?

小智 14

从历史上我们学会了使用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>
Run Code Online (Sandbox Code Playgroud)

此外,这种技术不适用于某些元素(包括现代浏览器,按规格)

<!-- 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)
Run Code Online (Sandbox Code Playgroud)

但是,使用width:auto属性分析正常静态流中发生的情况

<div style="width:auto;padding:20px;margin:20px;background:lime;">a</div>
Run Code Online (Sandbox Code Playgroud)

你会发现它与...非常相似

<div style="width:auto;padding:20px;margin:20px;background:lime;
    position:absolute;top:0;left:0;bottom:0;right:0;">b</div>
Run Code Online (Sandbox Code Playgroud)

...具有相同值的相同属性!这真的很棒!否则它看起来像:

<div style="width:100%;height:100%;
    position:absolute;top:0;left:0;">
    <div style="padding:20px;margin:20px;
        background:lime;">c</div>
</div>
Run Code Online (Sandbox Code Playgroud)

这也是不同的,因为内部div不填充y轴.要解决这个问题,我们需要css calc()或者box-sizing不必要的头痛.


我的答案是,left + right | top + bottom真的很酷,因为它们最接近静态定位width:auto ,没有理由不使用它们.他们是比较容易的方式相比,替代使用,它们提供了更多的功能(例如,使用margin-left,padding-leftleft在一个单一的元素在同一时间).

left + right | top + bottom与替代方案相比,浏览器更好地支持width:100% + box-sizing | calc() 它,它也更容易使用!

当然,如果你不需要(如你的例子中)在y轴上增长元素, width:100%使用一些嵌套元素作为填充,它也是MSIE6的归档支持的唯一解决方案.

所以,取决于你的需求.如果你想支持MSIE6(这是唯一的实际原因)你应该使用with:100%,否则使用left + right!

希望能有所帮助.