Home >Web Front-end >CSS Tutorial >How to Create Responsive CSS Triangles with Percentage Width?

How to Create Responsive CSS Triangles with Percentage Width?

Susan Sarandon
Susan SarandonOriginal
2024-12-07 02:16:15719browse

How to Create Responsive CSS Triangles with Percentage Width?

Generating Responsive CSS Triangles with Percentage Width

Problem:

Creating arrows below elements using CSS can be tricky as border widths for the arrow cannot be set in pixels. This makes it difficult to achieve a responsive triangle.

Solution:

To create a responsive triangle using CSS, you can use a skewed and rotated pseudo element.

Implementation:

  1. Create an outer container:

    .btn {
      position: relative;
      display: inline-block;
      width: 100px;  /* Set a fixed width for demonstration purposes */
      height: 50px;
    }
  2. Add the triangle:

    .btn:after {
      content: "";
      position: absolute;
      bottom: -10px;
      left: 0;
      width: 0;
      height: 0;
      border-width: 10px 50px 0 50px;
      border-style: solid;
      border-color: gray transparent transparent transparent;   
    }

Responsive Version:

To make the triangle responsive, modify the outer container and triangle styles as follows:

  1. Responsive Container:

    .btn {
      position: relative;
      display: inline-block;
      width: 50%;  /* Set a percentage width for responsiveness */
      height: 50px;
    }
  2. Responsive Triangle:

    .btn:after {
      top: 50px;  /* Adjust the top position */
      background-color: inherit;
      padding-bottom: 50%;
      width: 57.7%;
      transform-origin: 0 0;
      transform: rotate(-30deg) skewX(30deg);
    }

Note: The padding-bottom property maintains the triangle's aspect ratio. Removing the width on .btn allows the shape to adjust its size based on its content.

This CSS implementation creates a triangle with a percentage-based width that maintains its aspect ratio and adjusts its size based on the container's dimensions.

The above is the detailed content of How to Create Responsive CSS Triangles with Percentage Width?. 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