“填充父级”的 CSS?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5330895/
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
CSS for "fill parent?"
提问by Naftuli Kay
I have an item on the DOM that I'd simply like to have fill its parent's width, regardless of what that is:
我在 DOM 上有一个项目,我只想填充其父项的宽度,无论它是什么:
<div width="800">
<div class="filler"></div>
</div>
How can I specify in CSS that the filler
class match the width of its parent?
如何在 CSS 中指定filler
该类与其父类的宽度相匹配?
.filler {
?
}
采纳答案by BinaryTox1n
Have you tried: width: 100%;
?
你有没有试过:width: 100%;
?
回答by mingos
Depending on what you inner item is, there are various approaches.
根据您的内部项目是什么,有多种方法。
If it's a block-level element (a paragraph, a div, etc.), it will automatically adjust itself to fill 100% of the container's width.
如果是块级元素(段落、div 等),它会自动调整自身以填充容器宽度的 100%。
If it's an inline element, too bad for you, it won't accept width:100%
until you convert it to a block-level element: display:block
.
如果它是一个内联元素,对你来说太糟糕了,它不会接受,width:100%
直到你将它转换为块级元素:display:block
。
Floated elements are a special case: they will only span to the width of their inner content, even if they're block level elements. They require width:100%
.
浮动元素是一种特殊情况:它们只会跨越其内部内容的宽度,即使它们是块级元素。他们需要width:100%
.
Absolutely positioned elements are even tougher: they need width:100%
, but the container also needs a positioning context, eg. position:relative
.
绝对定位的元素甚至更难:它们需要width:100%
,但容器也需要一个定位上下文,例如。position:relative
.
Examples of all four cases: http://jsfiddle.net/dD7E4/
所有四种情况的示例:http: //jsfiddle.net/dD7E4/
回答by Simon Watiau
div is a block element and by default fill his parent.
if it doesn't you probably use float:left
or float:right
or display:inline
or your parent is not 800px.
(maybe you should try with style="width:800px"
or width="800px"
instead of width="800"
)
I usually put a color border to see how it works.
div 是一个块元素,默认情况下填充他的父元素。
如果不是,您可能使用float:left
或float:right
或display:inline
或您的父母不是 800px。
(也许您应该尝试使用style="width:800px"
或width="800px"
代替width="800"
)
我通常会放置一个颜色边框来查看它是如何工作的。
回答by Brant Bobby
Unless there's something stopping them, block-level elements such as div
and p
will always fill the entire width of their container. If you have an inline element such as a span
or an a
, you could style it as display: block
to turn it into a block-level element, but this will also put a line break before and after it.
除非有什么阻止它们,块级元素,例如div
和p
将始终填充其容器的整个宽度。如果您有一个内联元素,例如 aspan
或 an a
,您可以display: block
将它的样式设置为将其转换为块级元素,但这也会在其前后放置一个换行符。