如何使用 html/css 在英雄横幅中定位 H1、H2 和按钮?

问题描述 投票:0回答:1

尝试将 h2 放置在 h1 上方,将 h1 放置在英雄横幅中按钮上方,该横幅均匀地集中在 css 背景图像上。当使用相对和绝对位置时,文本不会响应窗口调整,并且按钮会在窗口调整时左右滑动。

<section id="hero">
<h2>WELCOME TO THE SHOP</h2>
<h1>BUY BOOKS</h1>
<a href="shop.html"> <button type="button" class="hero-button">Browse the Shop</button> </a>
</section>

#hero {
background-image: url(https://img.freepik.com/free-vector/comic-style-background-flat-design_23-2148793185.jpg?w=1380&t=st=1697860085~exp=1697860685~hmac=132d5319251471c70a9674ad2808da7990f26a6e24d2911be4c8dc6e0f6ab6ff);
background-size: cover;
background-position: center;
max-width: 100%;
height: 500px;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}

#hero h2 {
  color: #F79413;
  font-family: Helvetica;
  position: absolute;
  top: 150px;

}

#hero h1 {
  color: #F79413;
  font-family: Helvetica;
  text-align: center;
  position: absolute;
}

.hero-button {
  border: 1px solid #F79413;
  padding: 14px 80px 14px 65;
  cursor: pointer;
  font-weight: 700;
  font-size: 15px;
  position: absolute;
  top: 200px;
  left: 425px;
}
html css flexbox display
1个回答
0
投票

从技术上讲,您可以使用

position:absolute
+
transform: translate(-50%, -50%)
来对齐所有内容,但就您而言,Flexbox 或网格会更方便。

由于您将其标记为 Flexbox,因此这里有一个使用列方向的示例。 (用网格也可以轻松实现)

#hero {
  background-image: url(https://img.freepik.com/free-vector/comic-style-background-flat-design_23-2148793185.jpg?w=1380&t=st=1697860085~exp=1697860685~hmac=132d5319251471c70a9674ad2808da7990f26a6e24d2911be4c8dc6e0f6ab6ff);
  background-size: cover;
  background-position: center;
  max-width: 100%;
  height: 500px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

#hero h2 {
  color: #F79413;
  font-family: Helvetica;
}

#hero h1 {
  color: #F79413;
  font-family: Helvetica;
  text-align: center;
}

.hero-button {
  border: 1px solid #F79413;
  padding: 14px 80px 14px 65;
  cursor: pointer;
  font-weight: 700;
  font-size: 15px;
}
<section id="hero">
  <h2>WELCOME TO THE SHOP</h2>
  <h1>BUY BOOKS</h1>
  <a href="shop.html"> <button type="button" class="hero-button">Browse the Shop</button> </a>
</section>

© www.soinside.com 2019 - 2024. All rights reserved.