Html 使子 div 适合其父级宽度的跨浏览器方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6593425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cross browser method to fit a child div to its parent's width
提问by mate64
I'm looking for a solution to fit a child div
into it's parent's width
.
我正在寻找一种解决方案,让孩子div
适应其父母的width
.
Most solutions I've seen here are not cross-browser compatible(eg. display: table-cell;
isn't supported in IE <=8
).
我在这里看到的大多数解决方案都不是跨浏览器兼容的(例如display: table-cell;
,IE 不支持<=8
)。
回答by thirtydot
The solution is to simply not declare width: 100%
.
解决方案是简单地不声明width: 100%
.
The default is width: auto
, which for block-level elements (such as div
), will take the "full space" available anyway (different to how width: 100%
does it).
默认值为width: auto
,对于块级元素(例如div
),无论如何都会占用可用的“完整空间”(与width: 100%
它的方式不同)。
See:http://jsfiddle.net/U7PhY/2/
见:http : //jsfiddle.net/U7PhY/2/
Just in case it's not already clear from my answer: just don't set a width
on the child div
.
以防万一我的回答还不清楚:只是不要width
在 child 上设置 a div
。
You might instead be interested in box-sizing: border-box
.
相反,您可能对box-sizing: border-box
.
回答by Y.Puzyrenko
回答by Steeven
If you put position:relative;
on the outer element, the inner element will place itself according to this one. Then a width:auto;
on the inner element will be the same as the width of the outer.
如果你穿上position:relative;
外面的元素,里面的元素就会按照这个来放置自己。然后width:auto;
内部元素上的a将与外部元素的宽度相同。
回答by Alex
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.
在您的图像中,您已将填充放在孩子之外。不是这种情况。填充会增加元素的宽度,因此如果您添加填充并将其宽度设置为 100%,它将具有 100% + 填充的宽度。为了您想要什么,您只需要向父 div 添加填充,或向内部 div 添加边距。因为 div 是块级元素,它们会自动扩展到其父元素的宽度。
回答by Daniel Gruszczyk
You don't even need width: 100%
in your child div:
您甚至不需要width: 100%
在您的孩子 div 中:
回答by Joonas
In case you want to use that padding space... then here's something:
如果您想使用该填充空间......那么这里有一些东西:
All the colors are background colors.
所有的颜色都是背景色。