使用transform: translate(-50%,-50%);
使屏幕上绝对位置的div居中时,文本模糊。
我尝试了吨的不同解决方案(mostly from here和here),除了将div的宽度和高度设置为偶数。
即,如果高度为77px而不是76px,则内部文本模糊。同样,如果div宽度是163像素而不是162像素,那么它就很模糊。
是否可以确保动态div的宽度和高度为偶数?
使用JavaScript似乎是一劳永逸的事情,因为它不仅复杂,而且会导致元素在渲染后立即闪烁到不同的宽度(需要渲染以首先找到宽度),这对于用户看。
此外,我不能仅仅硬编码宽度和高度,因为内容是动态的。另外,如果我可以将宽度硬编码为100px,那么我什至不需要这个问题,因为我可以做类似transform: translate(calc(-50% - 50px),-50%);
的事情来回避这个问题。
这是一个代码示例:
.outer {
margin: 0 auto;
width: 500px;
border: 1px solid #ddd;
height: 50px;
position: relative;
}
.inner {
position: absolute;
left: 50%;
top: 25px;
transform: translate(-50%, -50%);
background-color: #dfdfdf;
padding: 5px;
font-family: Inter;
}
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
<div class="outer">
<div class="inner">
<b> asdf </b> blurrya
</div>
</div>
答案 0 :(得分:3)
如果您愿意再添加一个元素,则可以在绝对定位的元素内使用flex
来使最里面的元素居中,同时保持其从文档流中的排除。
.outer {
margin: 0 auto;
width: 500px;
border: 1px solid #ddd;
height: 50px;
position: relative;
}
.inner {
position: absolute;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.center {
top: 25px;
background-color: #dfdfdf;
padding: 5px;
font-family: Inter;
}
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
<div class="outer">
<div class="inner">
<p class="center">
<b>asdf </b> blurrya
</p>
</div>
</div>