HTML
display 하위 요소들의 크기 기준으로 flex 적용하기
탐훈
2024. 10. 5. 13:17
728x90
display:flex 자식 요소들은
부모의 크기에 알아서 맞춰진다.
부모의 크기가 결정되지 않고
자식의 크기를 설정해서 영역을 잡으려고 한다면 어떻게 해야될까
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="test-list">
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
</div>
</div>
</body>
</html>
<style>
.container {
width: 320px;
}
.test-list {
display: flex;
justify-content: space-between;
align-items: center;
gap:10px;
}
a {
width: 50px;
}
span {
background-color: yellow;
padding: 10px;
}
</style>
width 50px로 잡아놨지만 실제로는
span은 37px 정도로 잡혀져있다.
display:flex 를 사용하면
부모에서 정의한 width를
자식 갯수에 나눠서 갖는다.
부모에서 정의한 width를 무시하고
자식 요소에서 정한 width 만큼 가지려면 두가지 해결방법이 있다.
1. display:inline-flex; white-wrap:nowrap;
2. width:max-content;
inline-flex를 사용하는 경우
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="test-list">
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
</div>
</div>
</body>
</html>
<style>
.container {
width: 320px;
}
.test-list {
display: inline-flex;
justify-content: space-between;
align-items: center;
white-space: nowrap;
gap:10px;
}
span {
width: 50px;
}
span {
background-color: yellow;
padding: 10px;
}
</style>
2. width: max-content 사용하는 경우
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="test-list">
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
<span>테스트 글</span>
</div>
</div>
</body>
</html>
<style>
.container {
width: 320px;
}
.test-list {
display: flex;
justify-content: space-between;
align-items: center;
width: max-content;
gap:10px;
}
span {
width: 50px;
}
span {
background-color: yellow;
padding: 10px;
}
</style>
display: inline-flex; 를 사용하는 경우
span에 먹인 background-color가 안먹는다
white-space:nowrap; 을 사용해서 문제가 발생한다.
width 영역을 벗어남에도 불구하고 wrap 하지 않는다는 속성 때문이다.
부모에서 width를 미리 정해서
그 안에서 레이아웃을 잡아야 하는데
inline-flex를 사용하는 경우는
자주 일어나지는 않을 듯 하다.
그런데 작업을 하다보면
예상하지 못한 일들이 발생해서 이런 속성과 해결방법에 대해서 아는 것도 중요하다고 생각한다.