nkcmr
nkcmr

Reputation: 11000

How do I make an absolutely positioned element only use the necessary amount of width?

So I'm putting together some alert system for a website I'm building. Layout is pretty simple:

<style>
     #alert{
         position:absolute;
         padding:10px;
         display:table;
         margin:0 auto;
     }
</style>
<div id="alert">
    Hey user, I have a very important message for you.
</alert>

Now, if an element isn't absolutely positioned I normally use display:table to make sure it only takes the necessary amount of width, but absolutely positioning it kind of ruins that.

Is there a way to make it so that the element only takes the necessary amount of width, but still be absolutely positioned?

EDIT:
Basically what I am looking for is an absolutely positioned element that has dynamic width, and is centered.

Upvotes: 0

Views: 65

Answers (2)

nkcmr
nkcmr

Reputation: 11000

This seemed to do the trick:

<style>
    #alert {
         position:absolute;
         width:100%; /* Keep in mind this is for an entire page */
         height: 16px; /* Match the font-size of the alert */
         text-align:center;
         cursor:pointer;
    }
    #alert #inner_alert {
         display:inline-block;
         padding:10px;
    }
</style>
<div id="alert">
    <div id="inner_alert">Here is the message!</div>
</div>

This will produce a centered element that will only be as wide as it needs to be and is absolutely positioned.

Upvotes: 1

Rohit Azad Malik
Rohit Azad Malik

Reputation: 32182

Hey now you can used left or right properties as like this

#alert{
    position:absolute;
    padding:10px;
    left:0;
    right:0;
    top:0;
    bottom:0;
}

hey now you can define your value in left right top bottom as according your layouts

if you define position absolute than define your div width or height

now you can used this one live demo http://jsfiddle.net/YvMAJ/

Upvotes: 0

Related Questions