본문 바로가기
Mark Up/CSS

[CSS] Chapter 10. 레이아웃 만들기 - float

by song.ift 2022. 12. 29.

 

2. float 정렬

<div class="container">
  <div class="top"></div>
  <div class="left"></div>
  <div class="right"></div>
  <div class="botoom"></div>
</div>
.container {
  width: 400px;
  height: 600px;
  border: 1px solid black;
}

.top {
  background: red;
  width: 400px;
  height: 200px;
}

.left {
  background: blue;
  width: 200px;
  height: 200px;
}

.right {
  background: green;
  width: 200px;
  height: 200px;
}

.bottom {
  background: purple;
  width: 400px;
  height: 200px;
}

 

float 속성이 있는데 이것은 레이아웃 배치를 위해서 만들어진 속성이다.

html의 모든 태그들은 float이 디폴트로 none으로 부여되어 있다.

정렬을 해주고 싶은 방향에 따라 left, right로 설정해주면 된다.

.left {
  background: blue;
  width: 200px;
  height: 200px;
  float: left;
}

.right {
  background: green;
  width: 200px;
  height: 200px;
  float: right;
}

 

하지만 결과는 bottom 태그가 left와 right에 밑에 깔려있다.

깔려있는 걸 표현하기 위해 bottom 태그의 width를 100px 더 늘렸다.

왜 그런지 이해하기 쉽도록 비유를 해서 표현하자면, float : none 인 것들은 다 1층에 살고있다. 하지만 float에 left, right를 부여해주게 되면 그것들은 2층으로 올라간다. 그래서 하늘에서 봤다고 생각하고 left와 right는 2층으로 올라갔기 때문에 1층에 자리가 남아 bottom이 밑으로 들어가게 된것이다.

해결하려면 bottom에 clear : both 를 부여해주면 된다.

.bottom {
  clear: both;
  background: purple;
  width: 400px;
  height: 200px;
}

 

float 속성으로 정렬을 하고자 할 때는 어느 한쪽으로 정렬을 끝마친 이후에, 그 다음에 나와야 되는 영역에서 clear : both를 부여해주면 된다. 

float은 어느것을 기준으로 정렬을 하냐면 부모 태그의 기준으로 정렬한다. 간단하게 정렬할 때 float 속성을 이용하면 될 것 같다.

댓글