Position center 0.5px offset

Position center 0.5px offset

I haven't handwritten CSS for a long time.
Today, I encountered a problem that I feel is inexplicable. I
studied it carefully, but it has a deep charm.

The requirement is that divA is centered on the page, and B is positioned on top of A as a mask layer.

code block

I used the usual way of writing center positioning:

<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 pixel bias effect

You will find that there is a 0.5 pixel deviation on the left side of the gray mask layer! ! !

Later, the baby found the reason.
0.5px appears

Note: As you can see, left: 50% is based on the width of the phone. Because the width of the parent element of the positioned divB is the width of the body, 50% of the width of the mobile phone will appear 0.5px. Of course, mobile phones with different screen sizes have different situations, and some will deviate on the right side.

solution

Let's change the way of writing the positioning and centering:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325906119&siteId=291194637