bonny
bonny

Reputation: 3247

How to autosize a div?

I have a short question on how to autosize a div class.

I have some error messages that i would like to echo out. for this errormessages i have a div class:

.wrapper form .error {
    color: #ccc;
    position: absolute;
    z-index: 2;
    background-color:#fff;
    height: 26px;
    line-height: 26px;
    padding: 10px; 
    border: solid #ccc;
    border-width: 1px 1px 1px 1px;
    width: 200px; /*should be auto but doesnt work*/
    line-height: 26px;
    right: 100%;
    top: 7%;
} 

I would like to achieve that my different error message with different string lengths will be display in one line without breaks and the width of this div should be automatically sized depending from the length of the strings.

Upvotes: 3

Views: 20271

Answers (4)

Eli Gassert
Eli Gassert

Reputation: 9763

http://jsfiddle.net/REsm3/

By using white-space: nowrap you can achieve a one-line result like you want. However, to achieve the "auto width" styling as you call it, your element needs to be inline or inline-block. See my jsfiddle on how I'd change your markup to accomplish this. In short, I'd wrap the error in a common element, say class="message" and style that to text-align: center. Then I'd set the error to display: inline and thus achieve the "auto width" style you want.

<div class="message">
    <div class="error">
        This is an error message
    </div>
</div>

<div class="message">
    <div class="error">
        This is an error message. This is an error message. This is an error message.
    </div>
</div>

and the CSS:

.message
{
    text-align: center;
    margin-bottom: 10px;
}

.message .error
{
    border: 1px solid red;
    padding: 2px;
    white-space: nowrap;

    display: inline;
    display: inline-block;
}

Upvotes: 6

hsan
hsan

Reputation: 1559

white-space: nowrap; will keep the text on one line.

With display: inline; or display: inline-block the div will be as wide as necessary (and as narrow as possible) for the text to fit.

JS Bin example

Upvotes: 0

Barney
Barney

Reputation: 1848

The css rule:

white-space: nowrap;

will prevent your lines wrapping.

Set a width of the error div to 100% and it will automatically fill the space available. If you detail why you need to have the div automatically sized I might be able to help further.

Upvotes: 0

James Coyle
James Coyle

Reputation: 10428

Use white-space: nowrap; to keep it all on one line.

Upvotes: 0

Related Questions