“填充父级”的 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:57:14  来源:igfitidea点击:

CSS for "fill parent?"

css

提问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 fillerclass 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:leftor float:rightor display:inlineor 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:leftfloat:rightdisplay:inline或您的父母不是 800px。
(也许您应该尝试使用style="width:800px"width="800px"代替width="800"
我通常会放置一个颜色边框来查看它是如何工作的。

回答by Brant Bobby

Unless there's something stopping them, block-level elements such as divand pwill always fill the entire width of their container. If you have an inline element such as a spanor an a, you could style it as display: blockto turn it into a block-level element, but this will also put a line break before and after it.

除非有什么阻止它们,块级元素,例如divp将始终填充其容器的整个宽度。如果您有一个内联元素,例如 aspan或 an a,您可以display: block将它的样式设置为将其转换为块级元素,但这也会在其前后放置一个换行符。