首页 > 解决方案 > css中的图像和文本重叠,仅在图像上链接

问题描述

我正在尝试为我的网站制作一个新的横幅图像,其中横幅文本悬停在横幅图像上,并且横幅图像是一个链接。横幅文本没有链接。我也在尝试让这个横幅在响应式布局中工作。我之前使用了块元素和定位元素的组合,但我正在尝试使用 css 网格或 flexbox 实现更优雅的解决方案。

我的旧代码:

header {
  display: block;
  position: relative;
}

header img {
  display: block;
  position: relative;
  height: 100%;
  width: 100%;
}

header a {
  display: block;
  position: relative;
  width: 100%;
}

h1 {
  font: normal 2.8em "verdana", sans-serif;
  color: #ddd;
  position: absolute;
  right: 2vw;
  bottom: 4vh;
}
<header>
  <a href="index"><img src="https://www.placebear.com/800/200" alt="Banner Image" /></a>
  <h1>website title</h1>
</header>

新尝试的代码(flexbox + background-image 方法):

header {
  display: flex;
  height: 10vh;
  background-image: url("https://www.placebear.com/800/200");
  background-size: cover;
  padding: 2rem 0;
  color: #fff;
  text-shadow: 0px 1px 6px rgba(0, 0, 0, 0.6);
}

h1 {
  font-family: Arial, sans-serif;
  width: 80%;
  margin: 0 auto;
  line-height: 1.1em;
  font-size: 2rem;
}

@media (min-width: 500px) {
  h1 {
    font-size: 4rem;
  }
}
<a href="index">
  <header>
    <h1>
      example text
    </h1>
  </header>
</a>

我遇到的问题是链接标签不能仅应用于flexbox + background-image 方法中的图像。文本也包括在内,这不是我所追求的。

新尝试的代码(网格+链接):

header {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: repeat(3, 1fr);
}

header img {
  grid-column: 1;
  grid-row: 1 / 3;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

header p {
  grid-column: 1;
  grid-row: 2;
  align-self: center;
  justify-self: center;
  z-index: 1;
}
<header>
  <a href="#"><img src="https://www.placebear.com/800/200"></a>
  <p>SOME TEXT OVER IMAGE</p>
</header>

网格 + 链接方法不起作用,因为链接标签会破坏网格并强制自己在横幅图像下方创建另一个网格元素。

我真的在这里画了一根稻草,以弄清楚如何正确地实现这一点。如果有人有任何建议,那就太棒了。万分感谢!

标签: htmlcssflexboxcss-grid

解决方案


推荐阅读