如何創建:英雄圖像

學習如何使用 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;
}

親自試一試