Thuộc tính alignSelf dùng để căn chỉnh riêng một mục (item) bên trong container flex hoặc grid, ghi đè giá trị align-items của container cha.
Cú pháp
Để thiết lập alignSelf:
object.style.alignSelf = "auto|stretch|center|flex-start|flex-end|baseline|initial|inherit"
Các giá trị
| Giá trị | Mô tả |
|---|---|
| stretch | Kéo dãn item để lấp đầy container (mặc định). |
| center | Căn giữa item theo trục chéo. |
| flex-start | Căn item ở đầu container. |
| flex-end | Căn item ở cuối container. |
| baseline | Căn theo đường cơ sở (baseline) của container. |
| initial | Đặt về giá trị mặc định. |
| inherit | Kế thừa từ phần tử cha. |
Ví dụ
Ví dụ minh họa alignSelf:
<!DOCTYPE html> <html> <head> <style>
#container {
width: 180px;
height: 220px;
padding: 10px;
border: 1px solid #333;
display: flex;
align-items: baseline;
flex-flow: row wrap;
}
.ele {
width: 60px;
height: 60px;
background-color: skyblue;
}
.ele:nth-child(2n) {
background-color: orange;
}
</style>
<script>
function changeAlign(){
document.getElementsByClassName("ele")[1].style.alignSelf = "flex-end";
}
</script> </head>
<body>
<h2>Demo alignSelf</h2>
<div id="container">
<div class="ele"></div>
<div class="ele"></div>
<div class="ele"></div>
</div>
<p>Nhấn nút để thay đổi alignSelf của item thứ 2</p>
<button onclick="changeAlign()">THAY ĐỔI</button>
</body> </html>
Kết quả
Ban đầu các item căn theo baseline:

Sau khi nhấn nút, item thứ 2 chuyển xuống cuối (flex-end):
