Để đặt văn bản ở góc trên bên trá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 top và left.
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;
top: 10px;
left: 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 trên bên trá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 trên bên trái</div>
</div>
</body>
</html>
Bảng tóm tắt 4 góc + giữa
| Vị trí | CSS |
|---|---|
| Trên trái | top: 10px; left: 10px; |
| Trên phải | top: 10px; right: 10px; |
| Dưới trái | bottom: 10px; left: 10px; |
| Dưới phải | bottom: 10px; right: 10px; |
| Giữa chính giữa | top: 50%; left: 50%; transform: translate(-50%, -50%); |
Mở rộng: Image Caption/Overlay Component
.image-wrapper {
position: relative;
display: inline-block;
border-radius: 8px;
overflow: hidden;
}
.image-wrapper img {
display: block;
width: 100%;
height: auto;
transition: transform 0.3s;
}
.image-wrapper:hover img {
transform: scale(1.05);
}
.overlay {
position: absolute;
inset: 0;
background: linear-gradient(transparent, rgba(0,0,0,0.7));
display: flex;
flex-direction: column;
justify-content: flex-end;
padding: 1rem;
color: white;
opacity: 0;
transition: opacity 0.3s;
}
.image-wrapper:hover .overlay {
opacity: 1;
}
.caption-title { font-size: 1.25rem; font-weight: 600; }
.caption-desc { font-size: 0.875rem; opacity: 0.9; }
HTML Structure
<figure class="image-wrapper">
<img src="photo.jpg" alt="Mô tả ảnh">
<figcaption class="overlay">
<span class="caption-title">Tiêu đề</span>
<span class="caption-desc">Mô tả ngắn</span>
</figcaption>
</figure>