html5
와 css3
에서 float
을 쓸일은 아마도 거의 없을 것이다
display: flex
와 display: grid
로 해결이 안되는 것을 나는 아직까지는 본적이 없다
그럼에도 우리가 float
을 사용하고있는 사이트를 왕왕접하는 이유는 flex
와 grid
를 부분적으로 지원하거나 문법이 조금 다르기 때문이다
예를들면
repeat(12, 1fr 20px)
을 IE버전에서 사용하려면(1fr 20px)[12]
로 표현해야 한다
그럼 IE
를 버리면 되지 않느냐? 요즘 세상에 그걸 누가쓰냐
라는 말이 나올 수도 있는데 안타깝게도 한국에서는 10명 중 1명정도가 아직 IE
를 사용하고 있다
(제발 좀 빨리 사라져라 IE
)
(statcounter 기준 2020.02.~2021.02. 데스크탑 브라우저 점유율)
그래서 어쩔 수 없이 아직도 구식(?)인 float
을 사용하게 되는 경우가 있다
float
의 정의를 MDN에서 살펴보면
The float
CSS property places an element on the left or right side of its container, allowing text and inline elements to wrap around it. The element is removed from the normal flow of the page, though still remaining a part of the flow (in contrast to absolute positioning).
정의 말미에
CSS 속성 float
은 요소가 일반적인 배치흐름(normal flow)에서 빠져나온다
(하지만 아직도 절대적인 위치는 남아있는 상태)
그래서 예를들어
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</body>
</html>
와 같은 html
과
:root {
/* height and line-height */
--initial-pixel-size: 200px;
}
* {
margin: 0;
padding: 0;
border: 0;
list-style: none;
}
li {
width: 100px;
height: var(--initial-pixel-size);
color: white;
font-weight: 700;
text-align: center;
line-height: var(--initial-pixel-size);
}
li:first-child {
background-color: blue;
float: left; /* The element is removed from the normal flow */
}
li:nth-child(2) {
background-color: black;
}
li:last-child {
background-color: blueviolet;
}
css
을 적용하여 첫번째 li
는 정상적인 흐름에서 벗어나게 된다
쉽게 생각하면 layer
가 1과 0이 있는데 default가 0인데 float
을 쓰면 1이 된다고 생각하면 된다
근데 여기서 문제가 발생한다 출력된 화면을 보면
2번째 li
와 3번째 li
가 겹쳐있는 것을 볼 수 있다
이는 though still remaining a part of the flow (in contrast to absolute positioning) 이 문구에서 알 수 있듯이 절대적인 위치는 남아있기 때문이다
(width: 100px
과 height: 200px
의 공간은 아직 차지하고 있다)
그래서 2번째 li
의 배경색은 위로 올라가 자리를 메꾸지만
(1번째 li
의 text
와 line elements
는 layer_1
로 올라갔기 때문에)
2번째 li
의 text
는 위로 올라가지 못한 것을 알 수 있다
그래서 1번째 li
의 배경을 없애면
li:first-child {
/* background-color: blue; */
float: left;
}
li:nth-child(2) {
background-color: black;
}
li:last-child {
background-color: blueviolet;
}
이와 같이 배경색은 2번째 li
의 값인 black
이 되지만 여전히 1번째 li
의 공간은 할당되어 있는 모습을 볼 수 있다
여기서 우리는 여전히 공간은 할당되어 있지만 display
값이 변경됐음을 알 수 있다
li
는 원래 block level
인데 2번째 li
의 배경이 올라올 수 있다는 것은 inline
속성이기 때문임을 알 수 있고 inline
은 width
와 height
가 적용되지 않으므로 아마도 inline-block
이지 않을까 합리적 추측을 할 수 있다
중요한 것은 우리는 저렇게 올라가서 메꾸는 것을 원치 않을 때가 더 많다
이때 사용하는 것이 clear
이다
li:first-child {
background-color: blue;
float: left;
}
li:nth-child(2) {
background-color: black;
clear: both;
}
li:last-child {
background-color: blueviolet;
}
위로 올라가 메꾸려는 element
에게(통상적으로 float
을 한 바로 아래 element
)에게 clear
를 주는데 원래대로라면 float
의 value
에 맞춰서 left
와 right
를 구분해줘야 하지만 귀찮으니까 both
를 사용해 주기로 한다