css
をラップするとメディアクエリが楽に書けるようになります。
css
この関数は、styled[element]
テンプレートリテラルの中でさらに同じような書き方で書いたスタイルを埋め込みたい時につかいます。共通部分のスタイルを外部にまとめたいときとか便利なやつです。
import styled, {css} from 'styled-components';
const margin = css`
${props => props['data-margin'] || '10px'};
`;
const Div = styled.div`
margin: ${margin};
`;
margin
styled.div
margin
props
css
${desktop...}
...
const desktop = (first, ...interpolations) => css`
@media (max-width: ${sizes[label]}px) {
${css(first, ...interpolations)}
}
`;
media.desktop
media.tablet
import {css} from 'styled-components';
const sizes = {
desktop: 992,
tablet: 768,
phone: 576,
};
const media = Object.keys(sizes).reduce(
(acc, label) => {
acc[label] = (first, ...interpolations) => css`
@media (max-width: ${sizes[label]}px) {
${css(first, ...interpolations)}
}
`;
return acc;
},
{},
);
import {css, CSSObject, SimpleInterpolation} from 'styled-components';
const sizes: {[index: string]: number} = {
desktop: 992,
tablet: 768,
phone: 576,
};
const media = Object.keys(sizes).reduce(
(acc, label) => {
acc[label] = (
first: TemplateStringsArray | CSSObject,
...interpolations: SimpleInterpolation[]
) => css`
@media (max-width: ${sizes[label]}px) {
${css(first, ...interpolations)}
}
`;
return acc;
},
{} as {[index: string]: Function},
);