CSS/속성 - 띄움(정렬), 위치

float, float-display 수정

appmaster 2021. 1. 11. 15:52

요소를 좌우 방향으로 띄움(수평 정렬)

 

속성 값

의미 기본값
none 요소 띄움 없음 none
left 왼쪽으로 띄움  
right 오른쪽으로 띄움  
article .picture{
  width: 200px;
  height: 150px;
  background: tomato;
  float:left;
  margin-right: 20px;
  margin-bottom: 10px;
}

article .text{
  clear:left;
  /* clear는 흐르는 부분을 없애버린다. */
}

clear: left는 float의 흐르는 부분을 없애고, 왼쪽정렬로 하겠다는 뜻이다.

 

clear로 인해 다음줄로 이동하고 left로 인해 왼쪽정렬이 새로 시작한다.

 

 

 

수평정렬

.box{
  width: 150px;
  height: 100px;
  background:tomato;
  color:white;
  font-size:30px;
  margin:10px;
  float:right
}

float:right는 오른쪽에서부터 정렬이 시작된다.

 

 

float의 문제점

.box{
  width: 150px;
  height: 100px;
  background:tomato;
  color:white;
  font-size:30px;
  margin:10px;
  float:left;
}

.box4{
  width: 200px;
  height: 150px;
  background: orange;
}

float의 오류

float를 사용한 클래스에 다음, 다른 작업을 하게된다면 겹쳐버리는 현상이 생긴다. 이것을 해결하기 위해서 몇가지 방법이 있다.

 

 

clear: both;

.box{
  width: 150px;
  height: 100px;
  background:tomato;
  color:white;
  font-size:30px;
  margin:10px;
  float:left;
}

.box4{
  width: 200px;
  height: 150px;
  background: orange;
  clear: both;
}

clear를 이용함

clear: both; 를 이용하게된다면, 어떠한 정렬에 있어도 알아서 겹치지않게 설정이 된다.

 

 

float 해제

float 속성이 적용된 요소의 주위로 다른 요소들이 흐르게 되는데 이를 방지하기 위해 속성을 '해제'해야 함.

 

1. 형제요소에 clear: (left, right, both) 추가하여 해제

2. 부모요소에 overflow: (hidden, auto) 추가하여 해제

3. 부모요소에 clearfix 클래스 추가하여 해제(추천!)

 

 

**부모요소에 clearfix 클래스 추가하여 해제 하는 방법

float 속성이 추가된 요소의 부모요소에 미리 지정된 clearfix클래스 추가

<div class= "clearfix">
  <div class="float_box">1</div>
  <div class="float_box">2</div>
  <div class="float_box">3</div>
  <div class="float_box">4</div>
</div>
<div class="new-box"></div>
.clearfix::after{
  content: "";
  clear: both;
  display: block;
}

.float_box{
  width: 100px;
  height: 100px;
  background: orange;
  margin:10px;
  float: left;
}

.new-box{
  width: 240px;
  height: 250px;
  background: red;
}

*clearfix안에 있는 모든 요소는 무조건 float속성이 있어야 한다. 그래야지 다음 태그가 해제가 쉽게 된다.

 

 

 

display 수정

float 속성이 추가된 요소는 display속성의 값이 대부분 block으로 수정된다.

span{
  width: 100px;
  height: 100px;
  margin: 10px;
  background: tomato;
  float: left;
}

다음은 span태그 스타일로 float: left를 넣었다. inline요소인 span태그는 block요소로 바뀌는것을 확인 할 수 있다.

block요소가 된 span태그

그러므로 강제로 display: block으로 할 필요가 없다.