Home  >  Article  >  Web Front-end  >  How to Create a Hexagon with Border and Fill Using CSS Overlays?

How to Create a Hexagon with Border and Fill Using CSS Overlays?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 17:33:01259browse

How to Create a Hexagon with Border and Fill Using CSS Overlays?

Creating a Hexagon with Border and Fill

Hexagons are commonly created using CSS borders through pseudo elements. While it's not directly possible to fill a hexagon with one color and outline it with another, an alternative approach is to overlap multiple hexagons within each other.

Overlay Method

By overlaying hexagons, you can achieve the desired effect without relying on images. The following example demonstrates this method:

HTML:

<code class="html"><div class="hex">
    <div class="hex inner">
        <div class="hex inner2"></div>
    </div>
</div></code>

CSS:

<code class="css">.hex {
    /* Define shape, size, and colors */
    margin-top: 70px;
    width: 208px;
    height: 120px;
    background: #6C6;
    position: relative;
}

.hex:before, .hex:after {
    /* Create hexagon shape */
    content: "";
    border-left: 104px solid transparent;
    border-right: 104px solid transparent;
    position: absolute;
}

.hex:before {
    top: -59px;
    border-bottom: 60px solid #6C6;
}

.hex:after {
    bottom: -59px;
    border-top: 60px solid #6C6;
}

.hex.inner {
    /* Style inner hexagon */
    background-color: blue;
    transform: scale(.8, .8);
    z-index: 1;
}

.hex.inner:before {
    border-bottom: 60px solid blue;
}

.hex.inner:after {
    border-top: 60px solid blue;
}

.hex.inner2 {
    /* Style innermost hexagon */
    background-color: red;
    transform: scale(.8, .8);
    z-index: 2;
}

.hex.inner2:before {
    border-bottom: 60px solid red;
}

.hex.inner2:after {
    border-top: 60px solid red;
}</code>

This code creates three overlapping hexagons, each with different colors and z-index values. The transform: scale() property is used to proportionally decrease the dimensions of the inner elements, creating a layered effect.

Live Example

You can view a live example of this technique here: [Hexagon Border and Fill Example](https://codepen.io/username/pen/wveBJp)

The above is the detailed content of How to Create a Hexagon with Border and Fill Using CSS Overlays?. 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