Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Đặt nút bấm (Button) lên hình ảnh với CSS

Để đặt nút bấm chính giữa hình ảnh, sử dụng position: relative trên container và position: absolute kết hợp transform: translate(-50%, -50%) trên nút.

Ví dụ minh họa

<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      position: relative;
      width: 100%;
      max-width: 250px;
    }
    .box img {
      width: 100%;
      height: auto;
      display: block;
    }
    .box .btn {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 12px 24px;
      background: #e67e22;
      color: white;
      border: none;
      border-radius: 6px;
      font-size: 16px;
      cursor: pointer;
      white-space: nowrap;
    }
    .box .btn:hover {
      background: #d35400;
    }
  </style>
</head>
<body>
  <div class="box">
    <img src="https://www.tutorialspoint.com/videotutorials/images/current_affairs_home.jpg" alt="Current Affairs">
    <button class="btn">Nút bấm</button>
  </div>
</body>
</html>

Giải thích kỹ thuật căn giữa tuyệt đối

.centered {
  position: absolute;
  top: 50%;           /* Đích chuyển 50% từ trên */
  left: 50%;          /* Đích chuyển 50% từ trái */
  transform: translate(-50%, -50%); /* Kéo lùi 50% kích thước chính nó */
}

Các vị trí button phổ biến khác

Vị tríCSS
Trung tâmtop:50%; left:50%; transform:translate(-50%,-50%)
Trên giữatop: 20px; left: 50%; transform: translateX(-50%)
Dưới giữabottom: 20px; left: 50%; transform: translateX(-50%)
Giữa tráileft: 20px; top: 50%; transform: translateY(-50%)
Giữa phảiright: 20px; top: 50%; transform: translateY(-50%)

Overlay toàn màn hình (Modal style)

.overlay {
  position: fixed;
  inset: 0; /* top:0; right:0; bottom:0; left:0; */
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}