跨浏览器方法使子 div 适合其父级的宽度
我正在寻找一种解决方案,将子 div
放入其父级 width
中。
我在这里看到的大多数解决方案不跨浏览器兼容(例如,IE 不支持 display: table-cell;
<=8< /代码>)。
I'm looking for a solution to fit a child div
into it's parent's width
.
Most solutions I've seen here are not cross-browser compatible (eg. display: table-cell;
isn't supported in IE <=8
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
解决方案是简单地不声明
width: 100%
。默认值为
width: auto
,对于块级元素(例如div
),无论如何都会占用可用的“完整空间”(与width 的方式不同) :100%
做到了)。参见: http://jsfiddle.net/U7PhY/2/
只是如果我的回答还不清楚:只是不要在子
div
上设置width
。相反,您可能对
box-sizing: border-box
感兴趣。The solution is to simply not declare
width: 100%
.The default is
width: auto
, which for block-level elements (such asdiv
), will take the "full space" available anyway (different to howwidth: 100%
does it).See: http://jsfiddle.net/U7PhY/2/
Just in case it's not already clear from my answer: just don't set a
width
on the childdiv
.You might instead be interested in
box-sizing: border-box
.您可以使用
box-sizing
css 属性,它是跨浏览器(ie8+ 和所有真正的浏览器),对于这种情况来说是一个很好的解决方案:小提琴
You can use
box-sizing
css property, it's crossbrowser(ie8+, and all real browsers) and pretty good solution for such cases:Fiddle
如果将
position:relative;
放在外部元素上,内部元素将根据此元素放置自身。然后内部元素上的width:auto;
将与外部元素的宽度相同。If you put
position:relative;
on the outer element, the inner element will place itself according to this one. Then awidth:auto;
on the inner element will be the same as the width of the outer.在您的图像中,您已将填充物放在孩子外面。事实并非如此。内边距会增加元素的宽度,因此如果添加内边距并为其指定 100% 的宽度,它将具有 100% + 内边距的宽度。为了达到您想要的效果,您只需要向父 div 添加填充,或者向内部 div 添加边距。因为 div 是块级元素,所以它们会自动扩展到其父元素的宽度。
In your image you've putting the padding outside the child. This is not the case. Padding adds to the width of an element, so if you add padding and give it a width of 100% it will have a width of 100% + padding. In order to what you are wanting you just need to either add padding to the parent div, or add a margin to the inner div. Because divs are block-level elements they will automatically expand to the width of their parent.
您甚至不需要在子 div 中使用
width: 100%
:http: //jsfiddle.net/DanielDZC/w2mev/1/
You don't even need
width: 100%
in your child div:http://jsfiddle.net/DanielDZC/w2mev/1/
如果您想使用该填充空间...那么这里有一些内容:
http://jsfiddle.net/qD4zd/
所有颜色均为背景色。
In case you want to use that padding space... then here's something:
http://jsfiddle.net/qD4zd/
All the colors are background colors.