Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS for a text container between min and max width

Tags:

html

css

How can I style a DIV with text in it so that if takes the minimum length between a min-width and a max-width?

For example, if I have the min and max set at 200 and 400px, I want:

  • a div with text shorter than 200px to be 200px wide
  • a div with text between 200px and 400px to have the width of the text
  • a div with text longer than 400px to be wrapped

This jsFiddle I made explains it better: http://jsfiddle.net/LHFSn/ ...it sounds simple and straight forward but I just can't seem to figure it out.

And no, the obvious:

min-width: 200px;
max-width: 400px;

...doesn't give me what I want at all.

like image 562
NeuronQ Avatar asked Jul 12 '26 10:07

NeuronQ


2 Answers

Setting

display: inline-block

will allow you to achieve the desired result width-wise, but will also mean the elements will be displayed inline, that is, next to one another if they fit.
You can avoid this by wrapping your elements in block-style containers. While this sounds far from ideal it's the first idea off the top of my head that works.

Expanding on your further question, you can float these elements, wrap them in a container that's also displayed inline and then block it using Rúnar Berg's suggestion of empty blocks.

See sample jsFiddle
Clearfix reference

HTML:

ACTUAL:
<div></div>
<div class="wrapper cf">
<div class="flex-text">
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
</div>
<div class="flex-text">
    Lorem ipsum dolor sit amet.
</div>
<div class="flex-text">
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</div>
</div>
<div></div>
Further content

CSS:

.flex-text {
    min-width: 200px;
    max-width: 400px;
    display: inline-block;
    background: #def;
    float: left;
    clear: both;
}

/* this is just to show a 200px ruler for reference */
.flex-text:after {
    content: "";
    display: block;
    width: 200px;
    border-top: 4px solid black;
    margin: 0 0 20px 0;
}

.wrapper {
    display: inline-block;
    background: lightblue;
}

.cf:before,
.cf:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}
.cf:after {
    clear: both;
}
.cf {
    *zoom: 1;
}
like image 188
Etheryte Avatar answered Jul 15 '26 11:07

Etheryte


You can try to set the container display to table and the inner display to table-cell. It might get you into more trouble though.

http://jsfiddle.net/fXxV3/3/

like image 41
Rúnar Berg Avatar answered Jul 15 '26 11:07

Rúnar Berg