About
- Simple clone of CSS-in-JS libraries
- Inspired by styled-components and Emotion
- This page uses this library for styling!
- Visit here to see the code of the library and this page. Whole library code is contained in the single file.
Why
- To understand how CSS-in-JS libraries work
- To improve my knowledge
Goals
Goals
- Simple
- Lightweight
- Well-structured
Non-goals
- Performance
- Usable in production
APIs
css: Define a normal style
const myStyle = css`
color: red;
font-size: 16px;
`;
keyframes: Define an animation
const myAnimation = keyframes`
0% {
opacity: 0;
}
100% {
opacity: 1;
}
`;
styled: Attach the style on the tag or React component
const MyComponent = styled("div")`
color: red;
`;
Global: Inject global style into the page
<Global style={globalStyle} />
Examples
Basic example
const Button1 = styled("button")`
border: 1px solid black;
background-color: transparent;
`;
Pseudo class
const Button2 = styled("button")`
border: 1px solid black;
background-color: transparent;
&:hover,
&:active {
background-color: skyblue;
}
`;
Use other component
const Button3 = styled(Button2)`
font-weight: bold;
`;
Mix the styles
const roundedBorders = css`
border-radius: 10px;
`;
const putTransition = css`
transition: background-color 1s;
`;
const Button4 = styled(Button3)`
${roundedBorders}
${putTransition}
`;
Keyframes
const fadeIn = keyframes`
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
opacity: 0;
}
`;
const Button5 = styled(Button4)`
animation: 2s ${fadeIn} infinite;
`;
Use component props
interface Button6Props {
count: number;
onClick: () => void;
}
const Button6 = styled(Button3)<Button6Props>`
color: ${({ count }) => (count > 5 ? "red" : "black")};
`;