CSS flex-direction으로 div 위치 제어하기
JavaScript 환경에서 다른 div를 기준으로 특정 div의 위치를 설정하려면 CSS의 flex-direction 개념을 활용하는 것이 가장 간단합니다. 부모 컨테이너에 display: flex;를 적용하면 자식 요소들의 배치 방향과 순서를 자유롭게 제어할 수 있습니다.
예를 들어, 다음과 같은 CSS 스타일이 있다고 가정해 보겠습니다.
<style>
.demo{
display: flex;
flex-direction: column-reverse;
}
</style>
flex-direction: column-reverse;는 요소들을 세로 방향(column)으로 배치하되, HTML에 작성된 순서의 반대로 뒤집어 표시합니다. 즉, 코드상 먼저 선언된 div가 화면에서는 아래쪽에 나타나게 됩니다.
이제 위 스타일을 적용하여 두 개의 div 위치를 서로 기준으로 설정해 보겠습니다.
예제 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<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>
<script>
</script>
</body>
</html>
위 프로그램을 실행하려면 파일 이름을 "anyName.html(index.html)"로 저장한 뒤, VS Code 편집기에서 해당 파일을 마우스 오른쪽 버튼으로 클릭하세요. 이어서 "Open with Live Server(라이브 서버로 열기)" 옵션을 선택하면 브라우저에서 바로 결과를 확인할 수 있습니다.
실행 결과
위 코드를 실행하면 다음과 같은 출력 결과가 나타납니다.
