我一直在尝试将横幅图像放在顶部标题的文本后面,但格式似乎无法解决。
我也在样式表中尝试过background-image: url(/imgs/header_pic.jpg);,但是这样甚至没有显示出来。当前它显示在文本的后面,无法将图像居中或调整为最大高度,并且导航(列表项)也与图像重叠。



div#header-background {
  position: absolute;
  max-height: 4em;
  z-index: -1;
  border-radius: 10%;
  opacity: 0.25;
}

h1#header-text {
  position: relative;
  top: 0;
  text-align: center;
  font-size: 3em;
}

<body>
  <header>
    <div id="header-background"><img src="imgs/header_pic.jpg"></div>
    <h1 id="header-text">John Doe</h1>
  </header>
  <nav>
    <ul style="list-style-type: none">
      <li><a href="index.html">Main</a></li>
      <li><a href="about.html">about</a></li>
      <li><a href="contact.html">Contact</a></li>
    </ul>
  </nav>
  <main></main>
  <footer></footer>
</body>





更新:检查答案后(谢谢!)。我做了一些研究,并将其修改为以下代码。现在,我只需要垂直移动文本到中心,因为它不是居中对齐,而是有点偏离。
你们有什么感想?



header{
    width: 100%;
    height: 12em;
    position: relative;
  }

h1#header-text{
    position: absolute;
    z-index:999;
    text-align: center;
    font-size: 3em;
    width: 100%;
    height: 100%;
  }

header:after{
    content: "";
    position: absolute;
    top: 0px;
    width: 100%;
    height: 100%;
    background-image: url(imgs/header.jpg);
    background-position: center;
    background-repeat: no-repeat;
    background-size: contain;
    opacity: 0.25;
  }

最佳答案

当前的方式,可以通过将其添加到CSS中来隐藏溢出:

div#header-background{
    position: absolute;
    max-height: 4em;
    z-index: -1;
    border-radius: 10%;
    opacity: 0.25;
    overflow: hidden;
}


https://jsfiddle.net/f0xwbq73/2/

要应用背景图片,您可以这样操作:



header{
    background-image: url('https://www.gettyimages.com/gi-resources/images/CreativeLandingPage/HP_Sept_24_2018/CR3_GettyImages-159018836.jpg');
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
}

h1#header-text{
    position: relative;
    top: 0;
    text-align: center;
    font-size: 3em;
}

<body>
<header>
    <h1 id="header-text">John Doe</h1>
</header>
    <nav>
       <ul style="list-style-type: none">
          <li><a href="index.html">Main</a></li>
          <li><a href="about.html">about</a></li>
          <li><a href="contact.html">Contact</a></li>
       </ul>
    </nav>
    <main></main>
    <footer></footer>
</body>





但是,您将无法通过CSS控制图像的不透明度,因此您必须通过Photoshop或其他图像编辑器来实现。

https://jsfiddle.net/5g1zjLhw/

您可以检查https://www.w3schools.com/cssref/pr_background-image.asp以获取有关定位/尺寸调整的更多信息。

09-26 19:54
查看更多