How to autosize a div?

15,517

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;
}
Share:
15,517
bonny
Author by

bonny

Updated on June 04, 2022

Comments

  • bonny
    bonny almost 2 years

    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.