首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CSS:带背景图像的div上文字的六边形

CSS:带背景图像的div上文字的六边形
EN

Stack Overflow用户
提问于 2016-04-24 07:04:12
回答 1查看 1.7K关注 0票数 1

我有以下HTML和CSS代码:

代码语言:javascript
复制
.hex {
  width: 150px;
  height: 86px;
  background-color: #ccc;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-size: auto 173px;
  position: relative;
  float: left;
  margin: 25px 5px;
  text-align: center;
  zoom: 1;
}
.hex a {
  display: block;
  width: 100%;
  height: 100%;
  text-indent: -9999em;
  position: absolute;
  top: 0;
  left: 0;
}
.hex .corner-1,
.hex .corner-2 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: inherit;
  z-index: -2;
  overflow: hidden;
  backface-visibility: hidden;
}
.hex .corner-1 {
  z-index: -1;
  transform: rotate(60deg);
}
.hex .corner-2 {
  transform: rotate(-60deg);
}
.hex .corner-1:before,
.hex .corner-2:before {
  width: 173px;
  height: 173px;
  content: '';
  position: absolute;
  background: inherit;
  top: 0;
  left: 0;
  z-index: 1;
  background: inherit;
  background-repeat: no-repeat;
  backface-visibility: hidden;
}
.hex .corner-1:before {
  transform: rotate(-60deg) translate(-87px, 0px);
  transform-origin: 0 0;
}
.hex .corner-2:before {
  transform: rotate(60deg) translate(-48px, -11px);
  bottom: 0;
}
/* Custom styles*/

.hex .inner {
  color: #eee;
}
.hex h4 {
  font-family: 'Josefin Sans', sans-serif;
  margin: 0;
}
.hex hr {
  border: 0;
  border-top: 1px solid #eee;
  width: 60%;
  margin: 15px auto;
}
.hex p {
  font-size: 16px;
  font-family: 'Kotta One', serif;
  width: 80%;
  margin: 0 auto;
}
.hex.hex-3 {
  background: #80b971;
}
代码语言:javascript
复制
<div class="divWithBackgrounImage">
  <div class="hex hex-3">
    <div class="inner">
      <h4>CONTACT US</h4>
      <hr />
      <p>We Open Everyday</p>
    </div>
    <a href="#"></a>
    <div class="corner-1"></div>
    <div class="corner-2"></div>
  </div>
</div>

问题是,带有负值的z索引隐藏在背景图像的后面。如果我使用正z索引,那么我的六边形中就没有文本。如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-24 07:20:26

一个比CSS形状黑客更通用的解决方案是使用SVG。例如:

代码语言:javascript
复制
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="300" xmlns:xlink="http://www.w3.org/1999/xlink">
    <polygon class="hex" points="300,150 225,280 75,280 0,150 75,20 225,20" fill="#fa5" stroke="blue" stroke-width="5" transform="translate(10)"></polygon>
    <text x="160" y="160" 
        font-family="Verdana" 
        font-size="30"
        text-anchor="middle"
    >
    Any Text Here
    </text>  
</svg>

有许多可能性:

  • 有一个静态SVG,可以用作图像,也可以作为内联(如以下代码段所示)
  • 使用SVG作为带有文本的div的背景,或使SVG包含文本(如片段中所示)
  • 使用JavaScript动态设置图像中的文本(或其他属性,如颜色或大小)
  • 用JavaScript完全生成SVG (这是我通常的做法,我甚至有一个微库:hu.js),这个解决方案适合于完全动态的内容,而且越来越频繁。
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36820260

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档