Html 如何强制父 div 通过子 div 宽度/填充/边距/框展开?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17291514/
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
How to force parent div to expand by child div width/padding/margin/box?
提问by Chameleon
I want to expand div parent with child div but I don't know if that's possible and how to do it.
我想用子 div 扩展 div 父级,但我不知道这是否可能以及如何做。
I prepare a fiddleand included some code.
我准备了一个小提琴并包含了一些代码。
CSS
CSS
body {
background: gray;
}
div.page {
color: white;
background: black;
max-width: 72em;
margin: auto;
padding: 1em;
}
div.one {
background-color: red;
width: 40%;
}
div.two {
background-color: green;
width: 120%;
}
HTML
HTML
<body>
<div class="page">
<div class="one">One</div>
<div class="two">Two</div>
</div>
</body>
回答by bot
The key solution to your problem is to use display:inline-block;
HTML
您问题的关键解决方案是使用display:inline-block;
HTML
<div class="page">
<div class="one">One</div>
<div class="two">Two</div>
</div>
CSS
CSS
body {
background: gray;
}
div.page {
color: white;
background: black;
margin: auto;
padding: 1em;
display:inline-block;
}
div.one {
background-color: red;
width: 10em;
display:inline-block;
}
div.two {
background-color: green;
width: 40em;
display:inline-block;
}
Here is the working fiddle
这是工作小提琴
回答by G-Cyrillus
You cannot use % and expect box to overflow, else it never ends 100% turns 120%, but then 120% of 120%, becomes .. and so on. forget this idea, it cannot work.
您不能使用 % 并期望框溢出,否则它永远不会结束 100% 变为 120%,但随后 120% 的 120% 变为 .. 等等。忘记这个想法,它行不通。
Your CSS request is incoherent.
您的 CSS 请求不连贯。
Beside, to see an element to grow wider than window, one of the parent must be able to behave this way, mostly , content overflow and remain visible. (html/body or parent)
此外,要看到一个元素变得比窗口更宽,父元素之一必须能够以这种方式行事,主要是内容溢出并保持可见。(html/body 或父)
as far as i know only:
据我所知:
display:
table
inline-table
table-row
table-cell
table
inline-table
table-row
table-cell
Can let container grow as much as content does.
可以让容器和内容一样增长。
回答by Kyle
Your problem is this:
你的问题是这样的:
div.two {
background-color: green;
width: 120%;
}
You are telling the child to be 120% the width of the parent, which is to say, the entire width plus 20% more. Make it 100% and you should get the expected result..
你告诉孩子是父母宽度的 120%,也就是说,整个宽度加上 20%。使它 100%,你应该得到预期的结果..