어떻게 보면 굉장히 당연한 기능이지만, 저는 그동안 인식하지 못해 활용하지 못했던
margin을 통한 공백 채우기grid를 활용한 media query없이 반응형 구현위 2가지 CSS기법에 대해 소개해 보려 합니다.
지금까지 무언가 요소를 찢어놓을 때, flex의 space-between속성을 이용해 양 요소를 갈라놓았습니다.
<style>
.header {
display:flex;
justify-content: space-between;
}
</style>
<header class='header'>
<h1>제목</h1>
<nav>목록</nav>
</header>
위 코드처럼 요소를 양 끝으로 위치시키는 방법을 주로 사용하고 있었습니다.
flex를 이용해도 상관없지만 margin의 auto속성을 활용해 공백을 채우는 방법도 있습니다.
<style>
.header {
display:flex;
}
.header nav {
margin-left: auto;
}
</style>
<header class='header'>
<h1>제목</h1>
<nav>목록</nav>
</header>
위 코드처럼 margin을 auto로 설정하면 해당 방향의 빈 공간을 채우는 효과가 있습니다.
grid를 이용해 카드와 같은 목록을 리스트로 보여주고 싶을 경우 아래와 같이 media query를 통해 구현할 수 있습니다.
<style>
ul {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
@media (min-width: 1200px) {
ul {
grid-template-columns: repeat(5, 1fr);
}
}
</style>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
기존 3개의 카드를 배치 시켰지만, media query를 통해 1200px가 넘으면 5개의 카드를 균등 배분 해주었습니다.
이와 같이 처리할 수 있지만 break point가 많아지면 굉장히 번거롭습니다.
<style>
ul {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}
</style>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
grid의 auto-fill과 minmax를 활용해, 아이템의 넓이가 300px로 몇개 들어갈 수 있는지를 계산해 자동으로 반응형을 구현해 줍니다.
이렇게 한줄로 목록을 반응형으로 구성할 수 있게 됩니다.