Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Div as wide as it needs to be

Tags:

css

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.

In other words:

CSS:

.box {
    min-width:170px;
}

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

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

HTML:

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

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)

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.

like image 863
Ryan Avatar asked Aug 29 '11 14:08

Ryan


1 Answers

Is this (jsFiddle) what you're trying to accomplish?

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.

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.

like image 94
mjisrawi Avatar answered Nov 15 '22 16:11

mjisrawi