JavaScript에서 flexWrap 속성을 사용하면 플렉스 컨테이너 안의 유연한 항목(플렉스 아이템)들이 한 줄에 모두 배치될지, 아니면 공간이 부족할 때 다음 줄로 넘어갈지를 동적으로 제어할 수 있습니다.
flexWrap 속성의 주요 값
- nowrap: 기본값입니다. 모든 항목이 한 줄에 배치되며, 공간이 부족하면 항목의 크기가 줄어듭니다.
- wrap: 공간이 부족하면 항목이 다음 줄로 자동으로 넘어갑니다.
- wrap-reverse: wrap과 동일하게 줄 바꿈이 일어나지만, 줄의 배치 순서가 반대가 됩니다.
예제
아래 코드는 JavaScript에서 flexWrap 속성을 활용한 예제입니다. Set 버튼을 클릭하면 플렉스 항목이 줄 바꿈되지 않도록(nowrap) 설정됩니다.
<!DOCTYPE html>
<html>
<head>
<style>
#box {
border: 1px solid #000000;
width: 120px;
height: 150px;
display: flex;
flex-wrap: wrap;
}
#box div {
height: 50px;
width: 50px;
}
</style>
</head>
<body>
<div id = "box">
<div style = "background-color:orange;">DIV1</div>
<div style = "background-color:blue;">DIV2</div>
<div style = "background-color:yellow;" id = "myID">DIV3</div>
</div>
<p>flexWrap 속성 사용하기</p>
<button onclick = "display()">설정</button>
<script>
function display() {
document.getElementById("box").style.flexWrap = "nowrap";
}
</script>
</body>
</html>
코드 설명
위 예제에서 #box 요소는 display: flex;와 flex-wrap: wrap; 스타일이 적용된 플렉스 컨테이너입니다. 초기 상태에서는 세 개의 DIV 항목이 컨테이너 너비(120px)보다 공간이 부족해 두 줄로 나뉘어 배치됩니다.
버튼을 클릭하면 display() 함수가 실행되고, document.getElementById("box").style.flexWrap = "nowrap"; 코드를 통해 줄 바꿈이 비활성화됩니다. 그 결과 모든 항목이 한 줄에 강제로 배치됩니다.
이처럼 flexWrap 속성은 화면 크기나 콘텐츠 양에 따라 레이아웃을 유연하게 조정해야 하는 반응형 웹 디자인에서 매우 유용하게 활용됩니다.