文本隐藏在 CSS 个边框形状后面

Text hidden behind CSS border shapes

我正在尝试创建一个 h1 样式,用背景色包围文本。

    h1.skew {
        padding-left: 10px;
        text-decoration: none;
        color: white;
        font-weight: bold;
        display: inline-block;
        border-right: 50px solid transparent;
        border-top: 50px solid #4c4c4c;
        height: 0;
        line-height: 50px;
    }
    <h1 class="skew">HELLO WORLD</h1>

https://jsfiddle.net/zo32q98n/

此时文本显示在背景下方。如何让文本显示在棕色背景中?

您可以使用 pseudo-element 作为背景并设置 z-index: -1 使其显示在文本下方。

h1.skew {
  padding-left: 10px;
  text-decoration: none;
  color: white;
  font-weight: bold;
  display: inline-block;
  position: relative;
  height: 0;
  line-height: 50px;
}
h1.skew:before {
  content: '';
  z-index: -1;
  border-right: 50px solid transparent;
  border-top: 50px solid #4c4c4c;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}
<h1 class="skew">HELLO WORLD</h1>

您可以将文本换行成 span...

<h1 class="skew"><span class="text">HELLO WORLD</span></h1>

然后将以下内容添加到您的样式表...

span.text {
  position: relative;
  top: -50px;
}

这会将文本向上移动,使其显示在您定义的边框上方。

由于边框高 50px,您可以在内部插入相同数量的负边距:

h1.skew::before {
  content: '';
  display: block;
  margin-top: -50px;
}

body {
  background: #ddd;
}
h1.skew {
  padding-left: 10px;
  text-decoration: none;
  color: white;
  font-weight: bold;
  display: inline-block;
  border-right: 50px solid transparent;
  border-top: 50px solid #4c4c4c;
  height: 0;
  line-height: 50px;
}
h1.skew::before {
  content: '';
  display: block;
  margin-top: -50px;
}
<h1 class="skew">HELLO WORLD</h1>

您可以使用 CSS3 linear-gradient().

h1.skew {
  padding: 10px 80px 10px 10px;
  display: inline-block;
  color: white;
  background: #4c4c4c; /* fallback */
  background: linear-gradient(135deg, #4c4c4c 80%, transparent 80%);
}
<h1 class="skew">HELLO WORLD</h1>

或者,如果您使用 border-bottom 而不是 border-top 也没有问题。

body {
    background: #ddd;
}

h1.skew {
  padding-left: 10px;
  text-decoration: none;
  color: white;
  font-weight: bold;
  display: inline-block;

  border-right: 50px solid transparent;
  border-bottom: 50px solid #4c4c4c;

  height: 0;
  line-height: 50px;
}
<h1 class="skew">HELLO WORLD</h1>