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

Patricia Arquette
Release: 2024-11-20 21:54:20
Original
233 people have browsed it

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

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

Here's an example code:

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

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!

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