CSS_09_레이아웃스타일3

송지윤·2024년 1월 16일

CSS

목록 보기
13/20

배치 관련 스타일(position)

position은 요소의 위치를 지정하는 속성

position: relative; (상대적인)

  • 지정된 요소 내부에 다른 요소가 상대적인 위치를 지정할 수 있도록 기준이 되게 만드는 속성
  • 내부에 작성되는 요소에 위치 지정 시 top, bottom, left, right 속성을 사용할 수 있음

position: absolute; (절대적인)

  • 기본 요소의 배치 순서를 무시하고 지정된 절대 위치에 요소를 배치함

position: fixed; (고정된)

  • 항상 고정된 위치에 요소를 배치함
    (화면이 움직이든 말든 항상 같은 위치)

html code

<div class="container-1">
	<div class="first">first</div>
	<div class="second">second</div>
	<div class="third">third</div>
</div>

css code

div {
    border: 1px solid black;
    box-sizing: border-box;
}

.container-1 {
    border: 2px dashed red;
    position: relative;
}

.first {
    width: 300px;
    height: 300px;
    background-color: yellow;
}

.second {
    width: 200px;
    height: 200px;
    background-color: green;

    position: absolute;
    top: 50px;
    left: 50px;
}

.third {
    width: 100px;
    height: 100px;
    background-color: red;

    position: absolute;

    top: 100px;
    left: 100px;
}

position: relative; 안하면 요소를 안쪽으로 넣을 수 없음

position: absolute; 설정 안하면 아래로 차곡차곡 쌓임 안에 고정 안됨

요소를 영역 정가운데에 배치하기

html code

<div class="container-2">
	<div id="center"></div>
</div>

css code

.container-2 {
    width: 400px;
    height: 400px;
    position: relative;
}

#center {
    width: 50px;
    height: 50px;
    background-color: pink;

    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
}

정가운데 배치 공식 같은 거

position: fixed;

html code

<div class="fixed-area">
	<a href="#body-top">위쪽으로 이동</a>
</div>

css

.fixed-area {
    width: 120px;
    position: fixed;
    bottom: 50px;
    right: 50px;
}


스크롤을 움직여도 항상 그 자리에 고정되어있음

0개의 댓글