Home >Web Front-end >CSS Tutorial >How to Achieve a Slanted Edge on a Div Using a Skewed Pseudo Element?

How to Achieve a Slanted Edge on a Div Using a Skewed Pseudo Element?

DDD
DDDOriginal
2024-11-13 05:44:02545browse

How to Achieve a Slanted Edge on a Div Using a Skewed Pseudo Element?

Creating a Slanted Edge on a Div

Introduction

Achieving a slanted edge on a div using CSS can be challenging, especially when aiming for a responsive solution. This topic has been discussed before, but let's explore an alternative approach.

Using a Skewed Pseudo Element

To create a slanted background, we can employ a skewed pseudo element. This allows us to keep the text unaffected by the transform property.

The transform origin property positions the pseudo element's skew from the right bottom corner, while overflow:hidden; conceals the overflowing sections. Finally, a negative z-index places the pseudo element behind the div's content.

CSS Implementation

div {
  position: relative;
  display: inline-block;
  padding: 1em 5em 1em 1em;
  overflow: hidden;
  color: #fff;
}

div:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
  -webkit-transform-origin: 100% 0;
  -ms-transform-origin: 100% 0;
  transform-origin: 100% 0;
  -webkit-transform: skew(-45deg);
  -ms-transform: skew(-45deg);
  transform: skew(-45deg);
  z-index: -1;
}

body {
  background: url('https://farm3.staticflickr.com/2878/10944255073_973d2cd25c.jpg');
  background-size: cover;
}

HTML Usage

<div>slanted div text</div>
<div>
  slanted div text<br/>
  on several lines<br/>
  an other line
</div>
<div>wider slanted div text with more text inside</div>

The above is the detailed content of How to Achieve a Slanted Edge on a Div Using a Skewed Pseudo Element?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn