Home >Web Front-end >CSS Tutorial >How Can I Create Angled Corners in CSS Using Only :before and :after Pseudo-elements?

How Can I Create Angled Corners in CSS Using Only :before and :after Pseudo-elements?

Linda Hamilton
Linda HamiltonOriginal
2024-11-27 12:10:10486browse

How Can I Create Angled Corners in CSS Using Only :before and :after Pseudo-elements?

Angled Corners in CSS: A Detailed Solution

Creating angled corners using pure CSS is possible, although it presents certain challenges. To achieve this, it's necessary to utilize :before and :after elements within a parent container that has a border.

  1. Add a Border to the Container: Establish a border around the container element to define the visible boundary.
  2. Create a :before Element to Block a Corner: Add a :before element with a border-top style specified in pixels to create a solid perpendicular line. Offset this element by -1 pixel to account for the border of the container.
  3. Add a :after Element to Create an Inner Line: Introduce a :after element with a slightly smaller offset than the :before element. Set the border-top style of the :after element to a different color, such as white, to create a contrasting line within the cut-off area.

While this technique approximates the desired effect, it may introduce a slight issue with the thickness of the 45-degree line.

Example Code:

.cutCorner {
    position:relative; background-color:blue; 
    border:1px solid silver; display: inline-block;
}

.cutCorner img {
    display:block;
}

.cutCorner:before {
    position:absolute; left:-1px; top:-1px; content:'';
    border-top: 70px solid silver;
    border-right: 70px solid transparent;
}

.cutCorner:after {
    position:absolute; left:-2px; top:-2px; content:'';
    border-top: 70px solid white;
    border-right: 70px solid transparent;
}
<div class="cutCorner">
    <img class="" src="https://www.google.co.uk/logos/doodles/2013/william-john-swainsons-224th-birthday-5655612935372800-hp.jpg" />
</div>

The above is the detailed content of How Can I Create Angled Corners in CSS Using Only :before and :after Pseudo-elements?. 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