使Div与其需要的一样宽 [英] Make Div as wide as it needs to be

查看:100
本文介绍了使Div与其需要的一样宽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了解释我的问题,我试图使一个div足够宽,以适应动态生成的标题,而不包装它,但div也有其他内容,我想包装。

To explain my problem, I'm trying to make a div wide enough to accommodate a dynamically generated title without wrapping it, but the div also has other content, which I want to wrap.

换句话说:

CSS

.box {
    min-width:170px;
}

.box span.title {
    font-size:24px;
    white-space: nowrap;
}

.box span.text{
    font-size:10px;
    white-space: normal;
}

HTML: b

<div class="box">
   <span class="title">Title on one line</span><br />
   <span class="text">This is the main body of text which I want to wrap as
           required and have no effect on the width of the div.</span>
</div>

但是,这导致div扩展到足够宽以包含文本的主体一行,我想包装。我已经尝试过各种各样的安排CSS和把它们所有内部容器divs等,但我似乎不能得到的盒子是完全足够的,只包含标题没有包装(但不小于最小宽度)

However, this is causing the div to expand to be wide enough to contain the main body of text on one line, which I want to wrap. I've tried various arrangements for CSS and the putting them all inside container divs and the like but I can't seem to get the box to be exactly wide enough to contain only the title without wrapping (but not less than the min width)

在CSS中有没有办法吗?注意我不想设置一个最大宽度,因为这只是导致它成为一个静态大小,因为文本的主体总是足以达到最大宽度。

Is there any way to do this just in CSS? Note I don't want to set a max width as this just causes it to become a static size again, as the main body of text is always going to be enough to hit the max width. I also can't line break the body manually as it's dynamically generated.

推荐答案

这个(jsFiddle)你想要完成什么?

我刚刚添加了 display:table; 到.box的CSS。这会将主div扩展为标题跨度的宽度,但会折叠文本跨度。

I just added display: table; to .box's CSS. This expands the main div to the width of the title span but wraps the text span.

注意:您还可以设置一个常量宽度,以防止div扩展到窗口的宽度。这样,如果它大于您的常量宽度,它仍然会扩展到标题的宽度,但是如果用户拖出窗口,它将不会增长。在我的例子中,我添加了 width:100px; 来演示。

Note: You can also set a constant width to prevent the div from expanding to the width of the window. This way it will still expand to the width of the title if it is larger than your constant width, but will not grow if the user drags out the window. In my example I added width: 100px; to demonstrate.

这篇关于使Div与其需要的一样宽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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