Is it possible to display an image within a hexagon shape in HTML/CSS?
One approach to achieve this is by implementing a clipping mask using CSS3 transformations.
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>
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!