Home >Web Front-end >CSS Tutorial >Can I Display an Image Inside a Hexagon Using HTML and CSS?

Can I Display an Image Inside a Hexagon Using HTML and CSS?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 21:54:20357browse

Can I Display an Image Inside a Hexagon Using HTML and CSS?

Hexagon with Image Inside

Question

Is it possible to display an image within a hexagon shape in HTML/CSS?

Proposed Solution

One approach to achieve this is by implementing a clipping mask using CSS3 transformations.

Implementation

First, define the hexagon's shape using the following CSS class:

.hexagon {
  --base: 20px;
  --height: calc(var(--base) * sqrt(3) / 2);

  position: relative;
  width: var(--base) * 2;
  height: var(--height) * 2;
}

Then, utilize overflow hidden and CSS transforms to create the hexagon mask and place the image inside it:

.hexagon > img {
  width: 100%;
  height: 100%;
  object-fit: cover;

  clip-path: polygon(
    0 0,
    calc(100% - var(--base)) 0,
    100% calc(var(--height) * 0.5),
    100% calc(var(--height) * 1.5),
    calc(100% - var(--base)) 100%,
    0 100%
  );
}

Here's an example code:

<div class="hexagon">
  <img src="image.jpg" alt="Image inside hexagon" />
</div>

Considerations

This solution offers both cross-browser compatibility and clickable masked areas. By leveraging CSS3 transformations, it allows for a flexible way to work with non-rectangular shapes.

The above is the detailed content of Can I Display an Image Inside a Hexagon Using HTML and CSS?. 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