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

Căn chỉnh văn bản góc dưới bên phải hình ảnh với CSS

Để đặt văn bản ở góc dưới bên phải của hình ảnh, sử dụng position: relative trên container và position: absolute trên văn bản với bottom và right.

Ví dụ minh họa

<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      position: relative;
      display: inline-block;
      max-width: 100%;
    }
    img {
      width: 100%;
      height: auto;
      opacity: 0.6;
      display: block;
    }
    .direction {
      position: absolute;
      bottom: 10px;
      right: 19px;
      font-size: 13px;
      color: white;
      background: rgba(0,0,0,0.6);
      padding: 5px 10px;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <h1>Định vị văn bản trên hình ảnh</h1>
  <p>Hình ảnh dưới đây có văn bản ở góc dưới bên phải:</p>
  <div class="box">
    <img src="https://www.tutorialspoint.com/python/images/python_data_science.jpg" alt="Python Data Science">
    <div class="direction">Góc dưới bên phải</div>
  </div>
</body>
</html>

Bảng tóm tắt 4 góc

Vị tríCSS
Trên tráitop: 10px; left: 10px;
Trên phảitop: 10px; right: 10px;
Dưới tráibottom: 10px; left: 10px;
Dưới phảibottom: 10px; right: 10px;

Mở rộng: Badge thông báo trên avatar/icon

.avatar-wrapper {
  position: relative;
  display: inline-block;
}
.badge {
  position: absolute;
  top: -4px;
  right: -4px;
  background: #e74c3c;
  color: white;
  font-size: 11px;
  font-weight: bold;
  min-width: 18px;
  height: 18px;
  border-radius: 9px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid white;
}

Mẹo: Responsive text overlay

.image-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 1rem;
  background: linear-gradient(transparent, rgba(0,0,0,0.8));
  color: white;
  font-size: clamp(0.875rem, 2vw, 1.125rem);
}