如何创建:图片上的按钮

学习如何使用 CSS 将按钮添加到图片上。

图片上的按钮

Mountains

亲自试一试

如何在图像上添加按钮

第一步 - 添加 HTML:

<div class="container">
  <img src="img_snow.jpg" alt="Snow">
  <button class="btn">Button</button>
</div>

第二步 - 添加 CSS:

/* 需要容器来定位按钮。根据需要调整宽度 */
.container {
  position: relative;
  width: 50%;
}

/* 使图片自适应响应式布局 */
.container img {
  width: 100%;
  height: auto;
}

/* 为按钮设置样式,并将其放置在容器/图像的中央 */
.container .btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  background-color: #555;
  color: white;
  font-size: 16px;
  padding: 12px 24px;
  border: none;
  cursor: pointer;
  border-radius: 5px;
}

.container .btn:hover {
  background-color: black;
}

亲自试一试