position

position

position프로퍼티는 요소의 위치를 지정합니다. position의 종류는 4가지가 있습니다.

static

staticposition의 기본값으로 기본적인 요소의 배치 순서에 따라 위에서 아래로, 좌에서 우로 배치됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<head>
<style>
#boxOne{
height: 300px;
width: 300px;
background-color: yellow;
position: static;
}
#boxTwo{
height: 300px;
width: 300px;
background-color: green;
position: static;
}
</style>
</head>
<body>
<div id="boxOne">
<div class="box-child"></div>
</div>
<div id="boxTwo">
<div class="box-child"></div>
</div>
</body>

위 코드로 작성하면 아래와 같이 두개의 박스가 생성되고 positionstatic이므로 기본상태로 배치됩니다.

fixed

fixed는 부모의 요소와 관계없이 브라우저의 화면에 고정되어 스크롤로 이동하더라도 화면에서 사라지지 않고 항상 같은곳에 고정됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<head>
<style>
#boxOne{
height: 300px;
width: 300px;
background-color: yellow;
position: static;
}
#boxTwo{
height: 300px;
width: 300px;
background-color: green;
position: fixed;
}
</style>
</head>
<body>
<div id="boxOne">
<div class="box-child"></div>
</div>
<div id="boxTwo">
<div class="box-child"></div>
</div>
</body>

위 코드로 작성하게 되면 boxOne은 기본값이므로 왼쪽위에 고정되어 스크롤 하게 되어도 페이지를 따라 올라가게 됩니다. 하지만 boxTwofixed값을 주었기때문에 브라우저에 고정되고 스크롤로 이동하더라도 고정된 위치에 있게 됩니다.

absolute

부모 요소 또는 조상 요소를 기준으로 위치가 결정됩니다. 하지만 부모 또는 조상요소에 position: relative;가 선언되지 않았다면 브라우저 화면을 기준으로 좌표값에 맞게 위치하게 됩니다. 따라서 조상요소에 position: relative;를 선언해주어야 원하는 위치에 놓을 수 있습니다.

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
<head>
<style>
body{
height: 400;
background-color: red;
}
.abs-box{
width: 400px;
height: 400px;
background: yellow;
}
.abs-child{
width: 100px;
height: 100px;
background-color: green;
position: absolute;
right: 0;
}
</style>
</head>
<body>
<div class="abs-box">
<div class="abs-child"></div>
</div>
</body>

위 코드대로 작성하게 되면 abs-box의 자식요소로 abs-child가 있지만 abs-child는 아래와 같이 부모요소를 벗어나 브라우저 화면의 오른쪽에 붙게 됩니다.

relative

absolute를 사용하기 위해 부모 요소에 relative를 사용합니다.

위와 같이 부모요소를 벗어난 자식요소를 부모요소 안에 넣기 위해서는 부모요소에 relative를 선언해주어야합니다.

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
<head>
<style>
body{
height: 400;
background-color: red;
}
.abs-box{
width: 400px;
height: 400px;
background: yellow;
position: relative;
}
.abs-child{
width: 100px;
height: 100px;
background-color: green;
position: absolute;
right: 0;
}
</style>
</head>
<body>
<div class="abs-box">
<div class="abs-child"></div>
</div>
</body>

위 코드와 같이 부모요소에 position: relative;를 선언하게 되면 아래와 같이 부모요소 안으로 자식요소가 들어오게 됩니다.

공유하기