Fjott
Fjott

Reputation: 1137

Text hidden behind CSS border shapes

I am trying to create a h1 style that is surrounding the text with a background color.

    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/

At this point the text appears beneath the background. How can I make the text appear inside the brown colored background?

Upvotes: 5

Views: 802

Answers (5)

Stickers
Stickers

Reputation: 78686

You can use 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>

Upvotes: 3

Eternal
Eternal

Reputation: 316

Alternatively there is no problem if you use border-bottom instead of 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>

Upvotes: 1

Oriol
Oriol

Reputation: 288270

Since the border is 50px tall, you can insert a negative margin of the same amount inside:

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>

Upvotes: 3

Rik Lewis
Rik Lewis

Reputation: 749

You can wrap the text in a span...

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

And then add the following to your stylesheet...

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

This will move the text up so that it appears over the border you've defined.

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122057

You can use pseudo-element for background and set z-index: -1 so it appears under the text.

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>

Upvotes: 4

Related Questions