尝试将伪元素居中时有间隙

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

我有一个

button
,我尝试在其中心添加一个
::before
伪元素 但当我尝试时,我发现了一个小间隙,我无法删除

我使用FireFox,这是运行代码时的结果

注意:我需要

::before
position: absolute;

为中心

它不应该有白色像素

body { 
    background: #111;
}

button {
    display: block;
    width: 15px;
    height: 15px;
    border: 1px solid #07f;
    position: relative;
    background: #fff;
}

button::before { 
    content: "";
    width: 100%;
    height: 100%;
    background: rgb(0, 209, 105);
    position: absolute;
    left: 50%;
    top: 50%;
    translate: -50% -50%;
}
<button></button>

html css pseudo-element
1个回答
0
投票

如果

:before
width: 100%; height: 100%;
那你为什么要把它与
translate
居中呢?应用
inset
并缩短代码:

body { 
  background: #111;
}

button {
  display: block;
  width: 15px;
  height: 15px;
  border: 1px solid #07f;
  position: relative;
  background: #fff;
}

button::before { 
  content: "";
  position: absolute;
  inset:0;
  background: rgb(0, 209, 105);
}
<button></button>

如果需要平移,请在尺寸上添加 1px 并

button { overflow: hidden; }
:

body { 
  background: #111;
}

button {
  display: block;
  width: 15px;
  height: 15px;
  border: 1px solid #07f;
  position: relative;
  background: #fff;
  overflow:hidden;
}

button::before { 
  content: "";
  position: absolute;
  width: calc(100% + 1px);
  height: calc(100% + 1px);
  left: 50%;
  top: 50%;
  translate:-50% -50%;
  background: rgb(0, 209, 105);
}
<button></button>

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