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

Thuộc tính alignSelf trong HTML DOM Style

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ả
stretchKéo dãn item để lấp đầy container (mặc định).
centerCăn giữa item theo trục chéo.
flex-startCăn item ở đầu container.
flex-endCăn item ở cuối container.
baselineCăn theo đường cơ sở (baseline) của container.
initialĐặt về giá trị mặc định.
inheritKế 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:

Thuộc tính alignSelf trong HTML DOM Style

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

Thuộc tính alignSelf trong HTML DOM Style