Home > Web Front-end > CSS Tutorial > How to Create a Slanted Div Without Using Borders in CSS?

How to Create a Slanted Div Without Using Borders in CSS?

Susan Sarandon
Release: 2024-11-11 08:08:03
Original
284 people have browsed it

How to Create a Slanted Div Without Using Borders in CSS?

Creating a Slanted Div Without Using Borders

Problem:

Creating a slanted div using borders is not feasible when the div is placed over an image. How can a slanted edge be created using CSS that is also responsive?

Solution:

A skewed pseudo element can be used to create the slanted background. This approach keeps the text unaffected by the transform operation. Here's how to achieve it:

  1. Position the Pseudo Element:
    Add an :after pseudo element to the div with absolute positioning.
  2. Define the Skew:
    Use the -webkit-transform: skew(-45deg); property (or its vendor prefixes) to skew the pseudo element by 45 degrees.
  3. Set the Transform Origin:
    Specify the transform-origin: 100% 0; to allow the pseudo element to skew from the right bottom corner.
  4. Hide Overflow:
    Add overflow: hidden; to the pseudo element to hide the overflowing parts.
  5. Stack Behind Content:
    Use a negative z-index on the pseudo element to stack it behind the content of the div.

Example Code:

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;
}
Copy after login

HTML:

<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>
Copy after login

The above is the detailed content of How to Create a Slanted Div Without Using Borders in CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template