styled-media-query로 반응형 디자인 구현하기

Jin·2022년 3월 1일
0

React

목록 보기
6/17

styled-media-query는 styled-component와 같이 반응형 디자인을 구현할 때 좋습니다.

사용법은 정말 간단합니다.

일단 styled-media-query를 npm 혹은 yarn으로 설치합니다.

yarn add styled-media-query 혹은 npm install styled-media-query

그 후에, 전역적으로 영향을 미치는 최상위단의 파일에 (가령, styled-component를 사용하는 경우에는 GlobalStyles.js 내부)

import { createGlobalStyle } from "styled-components";
import { generateMedia } from "styled-media-query";
import reset from "styled-reset";

export const customMedia = generateMedia({
    desktop: '78em',
    tablet: '60em',
    mobile: '46em'
})

const globalStyles = createGlobalStyle`
    ${reset};
    
    a {
        text-decoration: none;
        color: inherit;
    }
    * {
        box-sizing: border-box;
    }
    body {
        font-family: NanumGothic;
        font-size: 12px;
        background-color: rgba(20, 20, 20, 1);
        color: white;
        padding-top: 50px;
    }

    #root {
        overflow: hidden;
    }
`;

export default globalStyles;

이런 식으로 generateMedia 안에 반응형 디자인의 기준이 되는 요소들을 선언해줍니다. 저같은 경우에는 데스크탑, 태블릿, 모바일로 분류하였고 그에 맞는 값을 주었습니다.

import React, { useMemo } from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import useRouter from "use-react-router";
import { customMedia } from "./GlobalStyles";

...

const Item = styled.li < { current: boolean }> `
	width: 70px;
	font-size: 16px;
	text-align: center;
	border-bottom: 5px solid ${props => (props.current ? "#4d96fb" : "transparent")};
	transition: border-bottom .5s ease-in-out;
	${customMedia.lessThan('mobile')`
		width: 100%;
		font-size: 15px;
	`}
`;

...

function Header() {
	const { match: { url }, location: { pathname } } = useRouter();

	return useMemo(() => (
		<Head>
			<List>
				<Item current={pathname === "/" || pathname.includes("/movie")}>
					<SLink to="/">Movies</SLink>
				</Item>
				<Item current={pathname === "/tv" || pathname.includes("/tv")}>
					<SLink to="/tv">TV</SLink>
				</Item>
				<Item current={pathname.includes("/search")}>
					<SLink to="/search">Search</SLink>
				</Item>
			</List>
		</Head>
	), [url]);
}

export default Header;

Item의 css 설정 부분의 마지막을 주목해주세요. 사실, 이것이 styled-media-query의 적용 방법의 전부입니다.

기존의 css 설정 부분에 추가적으로 customMedia을 선언하여 해당 기준에 부합할 경우 변경할 css 속성을 선언해줍니다. 저는 모바일일 경우 width와 font-size를 변경하고 싶어서 위와 같이 선언하였습니다.

lessThan 뿐만 아니라 greaterThan, between같은 함수들도 존재하니 상황에 맞게 사용하시면 되겠습니다.

이것이 styled-media-query의 사용법입니다. 정말 간단하고 코드도 정말 조금만 더 추가하면 되므로 반응형 디자인 구현에 정말 효과적인 모듈 같습니다.

참조: https://github.com/morajabi/styled-media-query

profile
배워서 공유하기

0개의 댓글