Html 如何使 div 动态更改为内容宽度,并在浏览器窗口更改大小时保持该宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13388257/
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 can I make a div dynamically change to content width and have it remain that width even as the browser window changes size?
提问by Daniel F. Dietzel
Take a look at this: (Scenario 1)
看看这个:(场景1)
#container {
height:150px;
border:1px solid pink;
width:1100px;
}
#widget {
display:inline-block;
width:100px;
height:100px;
background-color:red;
}?
Very simple. A div with a bunch of other divs within it. Parent div has a fixed width of ~1000 pixels, children divs are set to display:inline-block; When you make the browser window smaller than the parent, a scroll bar appears and you can scroll to see the rest.
很简单。一个包含一堆其他 div 的 div。父 div 的固定宽度约为 1000 像素,子 div 设置为 display:inline-block;当您使浏览器窗口小于父窗口时,会出现一个滚动条,您可以滚动查看其余部分。
Now take a look at this: (Scenario 2)
现在看看这个:(场景2)
#container {
height:150px;
border:1px solid pink;
float:left;
}
#widget {
display:inline-block;
width:100px;
height:100px;
background-color:red;
}?
Same parent and children, but the width of the parent is dynamically determined by the number of div children you place in it. Which is dandy. However, when you make the browser window smaller, the parent div becomes as wide as the window and the children start wrapping around, making the parent taller (Even though we set a fixed height!)
相同的父级和子级,但父级的宽度由您放置在其中的 div 子级的数量动态确定。这是花花公子。但是,当您将浏览器窗口缩小时,父 div 变得与窗口一样宽,并且子级开始环绕,使父级更高(即使我们设置了固定高度!)
How do I make the parent div
BOTH dynamic in width as in scenario 2, but then also keep its shape/height/width when the browser window gets smaller so we can get a scrollbar?
如何使父div
BOTH 的宽度在场景 2 中动态变化,但在浏览器窗口变小时时还保持其形状/高度/宽度,以便我们可以获得滚动条?
回答by Hymantheripper
Min-width
is the way to go:
Min-width
是要走的路:
#container {
height:150px;
border:1px solid pink;
min-width:1100px; // set the minimum width of the container to 1100px
width: 100%; // if the window size is bigger than 1100px, then make the container span the entire window
}
See a live example here.
在此处查看现场示例。
A hacky way to achieve is using the white-space
property as follows:
实现的一种hacky方法是使用该white-space
属性,如下所示:
#container {
border:1px solid pink;
white-space: nowrap;
}
#widget {
display: inline-block;
width:100px;
height:100px;
background-color:red;
}?
See a live example here
在此处查看现场示例
回答by MikeSmithDev
Updating answer to include the white-space line:
更新答案以包含空白行:
#container {
height:150px;
border:1px solid pink;
white-space:nowrap;
overflow:auto;
}