CSS / Tutorial / position의 값이 fixed일 때 가운데 정렬하는 방법
position의 fixed를 이용하여 요소의 위치를 고정시킬 수 있습니다. 예를 들어 상단에 고정되는 메뉴바를 만들 때 사용합니다. 그런데, fixed를 하면 요소가 한쪽으로 치우칩니다. 만약 가운데에 위치시키고 싶다면 어떻게 할까요? transform 속성으로 해결할 수 있습니다.
- 아래는 가운데에 위치한 두 요소가 있는 간단한 예제입니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>CSS</title>
<style>
body {
box-sizing: border-box;
font-family: Consolas, monospace;
}
.jb-b {
width: 400px;
height: 100px;
margin: 0px auto;
background-color: #000000;
}
.jb-c {
width: 600px;
height: 200px;
margin: 0px auto;
background-color: #666666;
}
</style>
</head>
<body>
<div class="jb-a">
<div class="jb-b"></div>
<div class="jb-c"></div>
</div>
</body>
</html>

- 위에 있는 요소를 position: fixed;를 이용하여 고정하면 왼쪽에 위치합니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>CSS</title>
<style>
body {
box-sizing: border-box;
font-family: Consolas, monospace;
}
.jb-a {
position: relative;
}
.jb-b {
width: 400px;
height: 100px;
margin: 0px auto;
background-color: #000000;
position: fixed;
}
.jb-c {
width: 600px;
height: 200px;
margin: 0px auto;
background-color: #666666;
}
</style>
</head>
<body>
<div class="jb-a">
<div class="jb-b"></div>
<div class="jb-c"></div>
</div>
</body>
</html>

- left: 50%;를 추가하여 시작 위치를 정가운데로 만듭니다.
- transform: translateX( -50% );를 추가하여 요소 크기의 50%만큼 왼쪽을 이동합니다.
.jb-b {
width: 400px;
height: 100px;
margin: 0px auto;
background-color: #000000;
position: fixed;
left: 50%;
transform: translateX( -50% );
}










