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

Định vị element xuống đáy container với CSS Flex (margin-top: auto)


Trong flex column, dùng margin-top: auto trên item cuối để đẩy nó xuống đáy.

Ví dụ 1: Text content

<!DOCTYPE html>
<html>
<head>
  <style>
    #container {
      display: flex;
      flex-direction: column;
      height: 300px;
      border: 2px solid #333;
      border-radius: 8px;
      padding: 20px;
      gap: 10px;
    }
    .item {
      padding: 10px;
      border-radius: 6px;
      background: #e0f7fa;
    }
    .item:nth-child(2), .item:nth-child(3) {
      margin-left: 15%;
      background: #e8f5e9;
    }
    .item:last-child {
      margin-top: auto;  /* Đẩy xuống đáy */
      background: #ffebee;
    }
  </style>
</head>
<body>
  <div id="container">
    <div class="item">Item 1 - Top</div>
    <div class="item">Item 2 - Middle</div>
    <div class="item">Item 3 - Middle</div>
    <div class="item">Item 4 - Bottom (margin-top: auto)</div>
  </div>
</body>
</html>

Ví dụ 2: Avatar top & bottom

<style>
  #container2 {
    display: flex;
    flex-direction: column;
    height: 400px;
    border: 2px solid #333;
    border-radius: 8px;
    padding: 20px;
  }
  .avatar { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; }
  #top { align-self: flex-start; }
  #middle1, #middle2 { margin-left: 20%; }
  #bottom { margin-top: auto; align-self: flex-end; }
</style>
<div id="container2">
  <img id="top" class="avatar" src="user1.jpg">
  <img id="middle1" class="avatar" src="user2.jpg">
  <img id="middle2" class="avatar" src="user3.jpg">
  <img id="bottom" class="avatar" src="user4.jpg">
</div>

Kết quả

  • Item 1,2,3 ở trên, Item 4 tự động xuống đáy container
  • Avatar 1 trên cùng, 2-3 giữa, 4 dưới cùng góc phải

Ứng dụng thực tế

  • Card: nội dung trên, nút action dưới cùng
  • Footer trong sidebar
  • Chat: tin nhắn mới nhất ở dưới