0

所以我正在为我正在建立的网站建立一些警报系统。布局非常简单:

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

现在,如果一个元素不是绝对定位的,我通常会使用display:table它来确保它只占用必要的宽度,但绝对定位它会破坏它。

有没有办法让元素只占用必要的宽度,但仍然绝对定位?

编辑
基本上我正在寻找的是一个绝对定位的元素,它具有动态宽度,并且居中。

4

2 回答 2

1

这似乎起到了作用:

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

这将产生一个居中的元素,该元素的宽度将仅与需要的宽度一样大,并且绝对定位。

于 2012-07-02T05:27:22.193 回答
0

嘿,现在您可以像这样使用left或属性right

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

嘿,现在您可以left right top bottom根据您的布局定义您的价值

如果你定义position absolute而不是定义你的 divwidth or height

现在你可以使用这个现场演示http://jsfiddle.net/YvMAJ/

于 2012-07-02T03:57:11.613 回答