首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[分享]css六边形排列

发布于 2024-11-11 15:40:27
0
16

CSS六边形排列是一种很有趣的网页排版方式,其效果让人印象深刻。下面我们就来介绍如何用CSS实现六边形排列。

.grid {
  display: grid;
  grid-gap: 20px;
  grid-template-columns: repeat(3, 1fr);
}

.hexagon {
  position: relative;
  width: 100px;
  height: 115.47px;
  background-color: #f1c40f;
  margin: 0 auto;
  transform: rotate(120deg);
}

.hexagon:before,
.hexagon:after {
  content: "";
  position: absolute;
  width: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
}

.hexagon:before {
  bottom: 100%;
  border-bottom: 57.74px solid #f1c40f;
}

.hexagon:after {
  top: 100%;
  width: 0;
  border-top: 57.74px solid #f1c40f;
}

.hexagon-text {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  color: #fff;
  text-align: center;
  transform: rotate(-120deg);
  line-height: 1.5;
} 

上面的代码实现了六边形的基本样式和布局。需要注意的是,我们使用了伪元素:before和:after来画出六边形的上下两个三角形,并使用transform: rotate来旋转六边形达到正常显示的效果。

接下来,我们可以为每个六边形添加文字,只需在.hexagon元素内部增加一个容器元素,并设置绝对定位,即可放置对应的文字内容。具体实现代码如下:

<div class="grid">
  <div class="hexagon">
    <div class="hexagon-text">
      <p>Hello, Hexagon!</p>
    </div>
  </div>
  <div class="hexagon">
    <div class="hexagon-text">
      <p>Hello, Hexagon!</p>
    </div>
  </div>
  <div class="hexagon">
    <div class="hexagon-text">
      <p>Hello, Hexagon!</p>
    </div>
  </div>
  <div class="hexagon">
    <div class="hexagon-text">
      <p>Hello, Hexagon!</p>
    </div>
  </div>
  <div class="hexagon">
    <div class="hexagon-text">
      <p>Hello, Hexagon!</p>
    </div>
  </div>
  <div class="hexagon">
    <div class="hexagon-text">
      <p>Hello, Hexagon!</p>
    </div>
  </div>
</div> 

最后,我们使用一个名为.grid的容器将所有的六边形排列起来,同时使用grid-template-columns属性和repeat函数来指定每行出现的六边形数量,并通过grid-gap属性指定六边形之间的间距。

这样,一个六边形排列效果就完成了,如果你想进一步优化效果,可以使用CSS3动画或者JS交互来增强用户体验。

评论
一个月内的热帖推荐
91云脑
Lv.1普通用户

62849

帖子

14

小组

291

积分

赞助商广告
站长交流