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

Đặt vị trí div tương đối so với div khác bằng CSS Flexbox

Sử dụng CSS Flexbox với flex-direction: column-reverse để đảo ngược thứ tự hiển thị các div con.

Ví dụ

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flexbox column-reverse</title>
    <style>
        .demo {
            display: flex;
            flex-direction: column-reverse;
        }
    </style>
</head>
<body>
    <div class="demo">
        <div class="demo1">DIV_DEMO1</div>
        <div class="demo2">DIV_DEMO2</div>
    </div>
</body>
</html>

Kết quả

Thứ tự hiển thị: DIV_DEMO2 ở trên, DIV_DEMO1 ở dưới (ngược với thứ tự HTML).

Giải thích: flex-direction: column-reverse sắp xếp các item theo cột từ dưới lên trên. Đây là giải pháp CSS thuần túy, không cần JavaScript.