在绝对定位元素中居中一个元素

3
我有一件相当简单的事情要做。我仍在处理CSS的所有陷阱,所以请耐心等待。我想基本上取一个div,将它放置在position: absolute; left: 10px; right: 10px; bottom: 10px,然后将其子元素水平居中在浏览器中。 这是我的尝试
HTML:
<div class="notificashun-holder">
    <div class="alert-message info notificashun">
        <p>Hello, World!</p>
    </div>
</div>

CSS:
.notificashun-holder {
    display: block;
    bottom: 10px;
    left: 10px;
    right: 10px;
    position: absolute;
}

.notificashun {
    display: inline-block;
    margin: 0 auto;
}

事实上,我正在使用Bootstrap,而alert-message类使项目display:block,因此我需要将它们“缩小”到正常大小(仅适合其内容的大小)。
有人能帮我做到这一点吗?我只需要让notificashun-holder距离浏览器左侧、右侧和底部各为十个像素,并且notificashun只需尽可能小并居中于notificashun-holder中。
1个回答

2

由于您在 .notificashun 中使用了一个 inline-block 元素,该元素会受到 text-align 属性的影响。因此,要使其居中,只需将 text-align: center; 属性应用于您的 .notificashun-holder

.notificashun-holder {
    display: block;
    bottom: 10px;
    left: 10px;
    right: 10px;
    position: absolute;

    /*New property:*/
    text-align: center;
}

不错,问题解决了!有没有更好的方法来实现我想要完成的任务? - Naftuli Kay
据我所知,如果你需要将该元素特定设置为“inline-block”,那么这大概是最好的方式,因为它可以方便地保持最小尺寸。你现在的做法完全没有问题。 - Nightfirecat
好的,谢谢。是的,我不能将它放在一行内,否则会破坏Bootstrap的CSS。谢谢! - Naftuli Kay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接