如何使div动态更改为内容宽度,并且即使浏览器窗口更改大小,它也保持该宽度? [英] How can I make a div dynamically change to content width and have it remain that width even as the browser window changes size?

查看:120
本文介绍了如何使div动态更改为内容宽度,并且即使浏览器窗口更改大小,它也保持该宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这个:(场景1)

#container {
    height:150px;
    border:1px solid pink;
    width:1100px;
}
#widget {
    display:inline-block;
    width:100px;
    height:100px;
    background-color:red;
}​

http://jsfiddle.net/DQFja/1/

非常简单.一个div,其中包含一堆其他div.父div的固定宽度为〜1000像素,子div设置为display:inline-block;当您使浏览器窗口小于父窗口时,会出现一个滚动条,您可以滚动查看其余部分.

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.

现在来看一下:(方案2)

Now take a look at this: (Scenario 2)

#container {
    height:150px;
    border:1px solid pink;
    float:left;
}
#widget {
    display:inline-block;
    width:100px;
    height:100px;
    background-color:red;
}​

http://jsfiddle.net/zZRq7/

父级和子级相同,但父级的宽度由放置在其中的div子级数动态确定.哪个花花公子但是,当您减小浏览器窗口的大小时,父div会变得与窗口一样宽,并且子级开始回绕,从而使父级变高(即使我们将高度设置为固定值!)

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!)

如何像场景2一样使父级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?

推荐答案

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
}

此处中查看实时示例.

一种骇人听闻的实现方式是使用white-space属性,如下所示:

A hacky way to achieve is using the white-space property as follows:

#container {
    border:1px solid pink;
    white-space: nowrap;
}
#widget {
    display: inline-block;
    width:100px;
    height:100px;
    background-color:red;
}​

此处

这篇关于如何使div动态更改为内容宽度,并且即使浏览器窗口更改大小,它也保持该宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆