Category: HTML/CSS

  • Ways to Center aTag Using HTML and CSS

    Ways to Center aTag Using HTML and CSS

    1. Dùng margin: auto (theo chiều ngang)

    <div class="parent">
      <div class="child">Center</div>
    </div>
    
    
    .parent {
      width: 400px;
      border: 1px solid #ccc;
    }
    .child {
      width: 100px;
      margin: 0 auto; /* Căn giữa ngang */
      background: lightblue;
    }
    

    2. Dùng Flexbox

    .parent {
      display: flex;
      justify-content: center; /* center ngang */
      align-items: center;     /* center dọc */
      height: 300px;
      border: 1px solid #ccc;
    }
    .child {
      background: lightgreen;
    }
    

    3. Dùng Grid

    .parent {
      display: grid;
      place-items: center; /* center cả ngang + dọc */
      height: 300px;
      border: 1px solid #ccc;
    }
    .child {
      background: lightcoral;
    }
    

    4. Dùng position: absolute + transform

    .parent {
      position: relative;
      height: 300px;
      border: 1px solid #ccc;
    }
    .child {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%); /* đẩy ngược lại để center */
      background: lightyellow;
    }
    

    5. Chỉ căn giữa ngang bằng text-align: center (nếu child là inline-block)

    .parent {
      text-align: center;
    }
    .child {
      display: inline-block;
      background: lightpink;
    }
    

    Kết luận

    • Nếu chỉ cần căn ngang → dùng margin: auto hoặc text-align: center.
    • Nếu cần cả ngang + dọc → nên ưu tiên Flexbox hoặc Grid.
    • Với layout phức tạp, position + transform vẫn là giải pháp linh hoạt.