如何创建:英雄图像

学习如何使用 CSS 创建英雄图像。

英雄图像是带有文本的大图像,通常放置在网页的顶部:

亲自试一试

如何创建英雄图像

第一步 - 添加 HTML:

<div class="hero-image">
  <div class="hero-text">
    <h1>I am Bill Gates</h1>
    <p>And I'm a Photographer</p>
    <button>Hire me</button>
  </div>
</div>

第二步 - 添加 CSS:

body, html {
    height: 100%;
}

/* 英雄图像 */
.hero-image {
  /* 使用 "linear-gradient" 为图像(photographer.jpg)添加暗色背景效果。这将使文本更易于阅读 */
  background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("photographer.jpg");

  /* 设置特定高度 */
  height: 50%;

  /* 将图像定位并居中,以便在所有屏幕上都能很好地缩放 */
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
}

/* 将文字放在图像中间 */
.hero-text {
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
}

亲自试一试