CSS&JS/⚡Thinkers

[JS] position:absolute로 masonry layout 구현하기

arancia_ 2026. 1. 9. 13:19

See the Pen masonry layout(벽돌형 레이아웃) by Oh Ikmyeong (@dpffpself) on CodePen.

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="ko">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>벽돌형 masonry</title>
    <link rel="stylesheet" href="./style.css">
    <script src="./main.js" type="module"></script>
</head>
 
<body>
    <h1>masonry</h1>
    <ul id="list">
    </ul>
</body>
 
</html>
cs

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@charset "UTF-8";
 
{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
 
body {
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
    width: 100%;
    min-height: 100vh;
    background: #fffafc;
}
 
#list {
    --_gap: 20px;
    position: relative;
    width: 90%;
    max-width: 1600px;
    margin: 40px auto;
    background: #000;
    border: 2px solid red;
    border-radius: 12px;
    container-type: inline-size;
    container-name: list;
}
 
.list-item {
    list-style-type: none;
    overflow: hidden;
    position: absolute;
    border: 1px solid black;
    border-radius: 14px;
    background: #fff;
}
 
@container list (width >=960px) {
    .list-item {
        width: calc((100% - var(--_gap) * 5) / 4);
    }
}
 
@container list (width < 960px) {
    .list-item {
        width: calc((100% - var(--_gap) * 3) / 2);
    }
}
 
@container list (width < 500px) {
    .list-item {
        width: calc(100% - var(--_gap) * 2);
    }
}
 
.list-item-visual {
    position: relative;
    width: 100%;
    aspect-ratio: 1 / var(--_ratio);
    background: #ccc;
}
 
.list-item-text {
    padding: 10px 10px 20px 10px;
}
cs

JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
let GAP = 20;
const $ul = document.getElementById("list");
 
for (let i = 0; i < 12; i++) {
    const $li = document.createElement("LI");
    $li.classList.add(`list-item`);
    $ul.appendChild($li);
 
    const $vis = document.createElement("DIV");
    $vis.classList.add(`list-item-visual`);
    $vis.style.setProperty("--_ratio", (Math.random() + 0.3).toFixed(2));
    $li.appendChild($vis);
 
    const $txt = document.createElement("P");
    $txt.classList.add(`list-item-text`);
    $txt.textContent = "LoremIpsum";
    $li.appendChild($txt);
}
 
requestAnimationFrame(() => {
    set_gap();
    resize_list();
    reposition_list_item();
});
 
window.addEventListener("resize", () => {
    set_gap();
    resize_list();
    reposition_list_item();
});
 
/**
 * 
 */
function set_gap() {
    GAP = $ul.offsetWidth >= 960 ? 20 : 10;
    $ul.style.setProperty("--_gap", `${GAP}px`);
}//set_gap
 
/**
 * 
 */
function resize_list() {
    let limit = (GAP * 1.5);
    const $$li = Array.from(document.querySelectorAll(".list-item"));
    requestAnimationFrame(() => {
        const max = $$li.reduce((acc, $curr) => {
            const topHei = $curr.offsetTop + $curr.offsetHeight;
            if (acc < topHei) {
                return topHei;
            }
            return acc;
        }, 0);
        $ul.style.height = `${limit + max}px`;
    });
}//resize_list
 
/**
 * 
 */
function reposition_list_item() {
    const $$li = document.querySelectorAll(".list-item");
 
    let rowCount = 0;
    const prevTopList = [];
 
    if ($ul.offsetWidth >= 960) {
        const itemWidth = ($ul.getBoundingClientRect().width - GAP * 5/ 4;
        $$li.forEach(($li, idx) => {
            const lastItem = idx % 4 === 3;
            let left = (GAP * ((idx % 4+ 1)) + ((idx % 4* itemWidth);
            $li.style.left = `${left.toFixed(2)}px`;
 
            const { height } = $li.getBoundingClientRect();
            const prevIdx = idx - 4;
            const top = prevIdx < 0 ? GAP : GAP + prevTopList?.[prevIdx];
            prevTopList.push(top + height);
            $li.style.top = `${top}px`;
 
            if (lastItem) { rowCount++; }
        });
 
    } else if ($ul.offsetWidth >= 500) {
        const itemWidth = ($ul.getBoundingClientRect().width - GAP * 3/ 2;
        $$li.forEach(($li, idx) => {
            const lastItem = idx % 2;
            const left = lastItem ? (GAP * 2+ itemWidth : GAP;
            $li.style.left = `${left.toFixed(2)}px`;
 
            const { height } = $li.getBoundingClientRect();
            const prevIdx = lastItem ? (rowCount * 2- 1 : (rowCount - 1* 2;
            const prevTop = prevIdx < 0 ? 0 : prevTopList?.[prevIdx];
            const top = GAP + prevTop;
            prevTopList.push(top + height);
            $li.style.top = `${top}px`;
 
            if (lastItem) { rowCount++; }
        });
    } else {
        const itemWidth = ($ul.getBoundingClientRect().width - GAP * 2);
        $$li.forEach(($li, idx) => {
            const left = GAP;
            $li.style.left = `${left}px`;
 
            const { height } = $li.getBoundingClientRect();
            const prevIdx = idx - 1;
            const prevTop = prevIdx < 0 ? 0 : prevTopList?.[prevIdx];
            const top = GAP + prevTop;
            prevTopList.push(top + height);
            $li.style.top = `${top}px`;
        });
    }
}//reposition_list_item
cs