본문 바로가기

웹/HTML&CSS

[HTML/CSS] box-sizing / 2021.08.28

* 참고 자료 : 코드잇 HTML/CSS 강의
<!DOCTYPE html>

<html>
	<head>
		<meta charset="utf-8">
		<title>box-sizing</title>
		<style>
			
		</style>		
	</head>

	<body>
		<h1>Ice cream</h1>
		<p class="p1">
		Ice cream, chillin', chillin'
			Ice cream, chillin'
			Ice cream, chillin', chillin'
			Ice cream, chillin'
			I know that my heart can be so cold
			But I'm sweet for you, come put me in a cone
			You're the only touch, yeah, that get me meltin'
			He's my favorite flavor, always gonna pick him
			You're the cherry piece, just stay on top of me, so
			I can't see nobody else for me, no
			Get it, flip it, scoop it
			Do it like that, ah yeah ah yeah
			Like it, love it, lick it
			Do it like la la la, oh yeah
			Look so good, yeah, look so sweet (hey)
			Lookin' good enough to eat
			Coldest with the kiss, so he call me ice cream
			Catch me in the fridge, right where the ice be
			Look so good, yeah, look so sweet (hey)
			Baby, you deserve a treat
			Diamonds on my wrist, so he call me ice cream
			You can double dip 'cause I know you like me
		</p>

	</body>
</html>

 

이 코드를 가지고 box-sizing에 대해 배워보자.

 

1. 먼저 h1 요소를 width: 300px, height: 200px로 설정하자.

웹페이지 검사를 눌러보면

 h1이 가로 300px, 세로 200px로 설정된 것을 볼 수 있다.

 

2. 이제, padding과 border을 추가해보자.

padding은 30px, border은 5px로 설정하겠다.

웹페이지를 새로고침을 해보면

 

h1의 내용물이 300x200이고 padding과 border의 크기는 따로 설정이 돼서 박스크기가 늘어난다.

 

3. 내용물이 300x200 크기인 것이 아니라 전체 박스의 크기, 즉 padding과 margin까지 합해서 300x200이 되도록 하려면 어떻게 해야 할까?

 

직관적으로 생각해보면 전체세로길이 300에서 border값(10)과 padding값(60)을 뺀 230px을 h1 세로 길이로 설정해주면 된다. 가로길이도 마찬가지로 전체가로길이 200에서 border값(10)과 padding값(60)을 뺀 130px을 h1 가로길이로 설정해주면된다.

width: 230px, height:130px로 고친 후 새로고침해 보면,

 

 

 

이렇게 전체 박스의 크기가 300x200으로 설정된 것을 확인할 수 있다.

하지만 매번 이런 식으로 하기는 너무 비효율적이다.

 

4. box-sizing: border-box;

이 코드를 사용하면 padding과 border을 추가해도 따로 계산해줄 필요 없이 원하는 일정한 박스크기로 나오게 된다.

 

	h1 {
		width: 300px;
		height: 200px;
		padding: 30px;
		border: 5px solid red;
		box-sizing: border-box;
    }

 

코드를 이와 같이 고치고 새로고침 해보면,

이렇게 우리가 width: 300px, height: 200px로 적었음에도 불구하고 우리가 원했던 전체 박스의 크기에 따라 h1요소의 가로세로 길이를 자동으로 계산해주었다.

 

5. box-sizing이 너무 편리하다 보니까 요새는 모든 요소에 다 추가를 해 주는 추세이다.

모든 요소에 같은 속성을 적용해 주고 싶다면,

 

* {
   box-sizing: border-box;
}

 

* 을 사용하면 된다.

개발을 할 때 이 코드를 쓰고 개발한다면 훨씬 편하게 개발할 수 있을 것이다.