当使用position:absolute时,无法将文本居中。

问题描述 投票:0回答:1

我正面临着魏氏行为与 span 当它的位置由 absolute.我想把文字放在一个圆圈里。

.close-icon {
  background: red;
  border-radius: 50%;
  color: #ffffff;
  display: flex;
  font-size: 0.5rem;
  height: 0.75rem;
  justify-content: center;
  width: 0.75rem;
  align-items: center;
  position: absolute;
  right: 0.625rem;
  top: 0.375rem;
}
<span class="close-icon">X</span>

输出。output with absolute

没有位置 absolute:

background: red;
border-radius: 50%;
color: #ffffff;
display: flex;
font-size: 0.5rem;
height: 0.75rem;
justify-content: center;
width: 0.75rem;
align-items: center;

:输出。output without absolute

我找不到任何解决办法,也找不到发生这种情况的原因。如果有人能对这种行为做出一些说明,那就太好了。

PS:当我删除 right: 0.625rem 那么它是完全对准中心的。

html css css-selectors css-position
1个回答
-1
投票

你可以用这种方法解决。

<style>
    .close-icon {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        justify-content: center;
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
        background: red;
        border-radius: 50%;
        color: #ffffff;
        font-size: 0.5rem;
        height: 0.75rem;
        width: 0.75rem;
        position: absolute;
        left: 50%;
        top: 50%;
        -webkit-transform: translate(-50%,-50%);
        -ms-transform: translate(-50%,-50%);
        transform: translate(-50%,-50%);
    }
</style>

但请考虑到你需要把它放在一个相对的元素里 这样它就能被放置在这个元素的中间了

© www.soinside.com 2019 - 2024. All rights reserved.