定位居中0.5px偏差

定位居中0.5px偏差

很久没手写css了,
今日遇到一个自己感觉莫名奇妙的问题,
仔细研究,却深有韵味。

需求是,divA居中页面,B要作为遮罩层定位在A的上面。

代码块

我用了常用的写居中定位的方式:

<div class='answer_content'>
    <div class="answer_contentBox">这是divA</div>
    <div class="answer_contentBox answer_contentBox_gray">这是divB</div>
</div>
.answer_content{
    position: relative;
    width: 100%;
    height: 287px;
}
.answer_contentBox{
    width: 335px;
    height: 287px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 8px;
    text-align: center;
    color: #666;
}
.answer_contentBox_gray{
    position: absolute;
    background: #333;
    opacity: .8;
    color: #fff;
    top: 0;
    left:50%;
    transform: translateX(-50%);
}

0.5像素偏差效果

大家会发现,灰色的遮罩层左边居然有0.5像素偏差!!!

后来本宝宝找到了原因。
出现0.5px

注意:可以看到,left:50%,是根据手机宽度来的。因为定位的divB的父元素的宽度是body的宽度,手机宽度的50%就会出现0.5px。当然不同屏幕大小的手机,情况不一,有的会在右边出现偏差。

解决方案

咱们换一种写定位居中的方式就好了:

.answer_contentBox_gray{
    position: absolute;
    background: #333;
    opacity: .8;
    color: #fff;
    top: 0;
    left:0;
    right:0;
    margin:0 auto
}

猜你喜欢

转载自blog.csdn.net/m0_37395016/article/details/79990952
今日推荐