边框半径和背景剪辑在伪元素上无法正常工作

时间:2018-06-08 15:30:09

标签: css

我正在尝试创建一个包含多个图层的按钮 - 因此我不得不使用伪元素。

为了澄清,我的按钮实际上是一个锚<a>

我遇到了一个伪元素的问题。我试图给它一个背景,同时在背景之外保留一个可触摸的目标。为此,我在内容上应用了背景剪辑。

除了应用的角落之外,一切都有效,但不是我期待的形状。

按钮2是我试图破解的设计 - 通过确保伪完美覆盖元素。

我现在认为我知道发生了什么,但不知道为什么以及如何解决它。 填充深6px,边界半径10px。半径计算为4px深和10px宽。

任何建议表示赞赏。

div {
  margin-bottom: 20px;
}

a, a::before {
  box-sizing: border-box;
}

a {
  background-color: red;
  border-radius: 10px;
  color: white;
  display: inline-block;
  height: 36px;
  line-height: 36px;
  min-width: 100px;
  position: relative;
  text-align: center;
  z-index: 1;
}

a::before {
  background-color: rgba(0, 255, 0, 0.5);
  border-radius: 10px;
  content: "";
  display: block;
  height: 48px;
  padding: 6px 0;
  position: absolute;
  top: -6px;
  left: 0;
  width: 100%;
  z-index: -1;
}

.button2::before, .button2a::before {
  background-clip: content-box;
}

.button2a {
  margin-left: 20px;
}
.button2a::before {
  background-color: blue;
}

.button3::before {
  background-clip: content-box;
  border-radius: 50%;
}
<div>
<p>This is a button with no background-clip - border-radius applied as expected<p>
  <p><a class="button1">button 1</a></p>
</div>
<div>
<p>This has same border-radius as above, but background-clip applied on content - overlay doesn't completely disappear - leaves odd shapes at corners as can be seen on blue button. I was expecting 10px corners to mirror center</p>
  <p><a class="button2">button 2</a><a class="button2a">button 2</a></p>
</div>
<div>
<p>This has same background-clip applied but uses a percentage for border-radius - seems to work as expected</p>
  <p><a class="button3">button 3</a></p>
</div>

1 个答案:

答案 0 :(得分:0)

  

我正在尝试创建一个包含多个图层的按钮

如果以不同的方式做事,而不是使用伪元素,您可以依靠多个背景来拥有多个图层:

&#13;
&#13;
a.button1 {
  background: 
   linear-gradient(to right,transparent 50%,blue 0),
   linear-gradient(to bottom,orange 50%,transparent 0),
   red;
  border-radius: 10px;
  color: white;
  display: inline-block;
  height: 36px;
  line-height: 36px;
  min-width: 100px;
  text-align: center;
}
&#13;
<a class="button1">button 1</a>
&#13;
&#13;
&#13;