npm.io
15.0.0 • Published 7h ago

styled-breakpoints

Licence
MIT
Version
15.0.0
Deps
0
Size
54 kB
Vulns
0
Weekly
0
Stars
557


styled-breakpoints
GitHub Workflow Status coverage status npm bundle size npm downloads npm version

Powerful CSS-in-JS media queries with SSR support.

Styled Components Logo     OR    Emotion logo



Preview

Inside components.

const Box = styled.div`
  background-color: pink;

  ${({ theme }) => theme.breakpoints.up('sm')} {
    background-color: hotpink;
  }

  ${({ theme }) => theme.breakpoints.up('md')} {
    background-color: red;
  }
`;

Outside of components.

import { useTheme } from 'styled-components'; // or '@emotion/react'

const Layout = () => {
  const theme = useTheme()
  const isMd = useMediaQuery(theme.breakpoints.up('md'));

  return <>{isMd && <Box />}</>;
};

Examples

Mobile First

From smallest to largest


Desktop First

From largest to smallest


Hook API


Documentation


Core concepts

  • Breakpoints act as the fundamental elements of responsive design. They enable you to control when your layout can adapt to a specific viewport or device size.

  • Utilize media queries to structure your CSS based on breakpoints. Media queries are CSS features that allow you to selectively apply styles depending on a defined set of browser and operating system parameters. The most commonly used media query property is min-width.

  • The primary goal is mobile-first responsive design.. Styled Breakpoints aims to apply the essential styles required for a layout to function at the smallest breakpoint. Additional styles are progressively added for larger screens. This approach optimizes your CSS, enhances rendering speed, and delivers an excellent user experience.


Getting Started

Installation
npm install styled-breakpoints@latest

# or

yarn add styled-breakpoints@latest

Configuration
File Structure
 theme/
 ├── index.ts
 └── styled.d.ts // or emotion.d.ts
 app.tsx

Available breakpoints

Styled Breakpoints includes six default breakpoints, often referred to as grid tiers, for building responsive designs. These breakpoints can be customized.

const breakpoints = {
  values: {
    xs: '0px',
    sm: '576px',
    md: '768px',
    lg: '992px',
    xl: '1200px',
    xxl: '1400px',
  }
};

Each breakpoint is based on common responsive design conventions and aligns with container widths that are multiples of 12. These breakpoints also correspond to widely used viewport ranges, but they are not tied to specific devices.

Instead, they provide a consistent foundation for building responsive layouts that work across most screen sizes.


Default Configuration

theme/index.ts

import { createStyledBreakpointsTheme } from 'styled-breakpoints';

export const theme = createStyledBreakpointsTheme();


Customization
Breakpoints

theme/index.ts

import { createStyledBreakpointsTheme } from 'styled-breakpoints';

export const theme = createStyledBreakpointsTheme({
  breakpoints: {
    values: {
      phone: '0px',
      mobile: '200px',
      laptop: '300px',
      desktop: '400px',
    }
  },
});

Merge with Another Theme

theme/index.ts

import { createStyledBreakpointsTheme } from 'styled-breakpoints';

const mainTheme = {
  fonts: ["sans-serif", "Lato"],
  fontSizes: {
    small: "1em",
    medium: "2em",
    large: "3em",
  },
} as const;

export const theme = {
  ...mainTheme,
  ...createStyledBreakpointsTheme(),
};

export type AppThemeType = typeof theme;


Using with Styled Components

Installation
npm install styled-components

# or

yarn add styled-components

theme/styled.d.ts

import "styled-components";
import { AppThemeType } from "./index";

declare module "styled-components" {
  export interface DefaultTheme extends AppThemeType {}
}


Using with Emotion

Installation
npm install @emotion/{styled,react}

# or

yarn add @emotion/{styled,react}

theme/emotion.d.ts

import "@emotion/react";
import { AppThemeType } from "./index";

declare module "@emotion/react" {
  export interface Theme extends AppThemeType {}
}


Integration into Your App

app.tsx

import { ThemeProvider } from 'styled-components'; // or '@emotion/react'
import styled from "styled-components"; // or '@emotion/styled'

import { theme } from './theme';

const Box = styled.div`
  display: none;

  ${({ theme }) => theme.breakpoints.up('sm')} {
    display: block;
  }
`;

const App = () => (
  <ThemeProvider theme={theme}>
    <Box />
  </ThemeProvider>
);

Media queries API

All media query functions cache their results to improve performance.


Min-width - up
const Box = styled.div`
  display: none;

  ${({ theme }) => theme.breakpoints.up('sm')} {
    display: block;
  }
`;

Will be converted to CSS:
@media (min-width: 768px) {
  display: block;
}


Max-width - down

We occasionally use media queries that go in the other direction (the given screen size or smaller):


const Box = styled.div`
  display: block;

  ${({ theme }) => theme.breakpoints.down('md')} {
    display: none;
  }
`;

Will be converted to CSS:
@media (max-width: 767.98px) {
  display: none;
}

Why subtract .02px? Browsers don’t currently support range context queries, so we work around the limitations of min- and max- prefixes and viewports with fractional widths (which can occur under certain conditions on high-dpi devices, for instance) by using values with higher precision.



Single breakpoint - only

There are also media queries and mixins for targeting a single segment of screen sizes using the minimum and maximum breakpoint widths.


const Box = styled.div`
  background-color: pink;

  ${({ theme }) => theme.breakpoints.only('md')} {
    background-color: rebeccapurple;
  }
`;

Will be converted to CSS:
@media (min-width: 768px) and (max-width: 991.98px) {
  background-color: rebeccapurple;
}


Range of breakpoints - between

Use between to target a range of breakpoints.


const Box = styled.div`
  background-color: gold;

  ${({ theme }) => theme.breakpoints.between('md', 'xl')} {
    background-color: rebeccapurple;
  }
`;

Will be converted to CSS:
@media (min-width: 768px) and (max-width: 1199.98px) {
  background-color: rebeccapurple;
}


useMediaQuery hook

features:

  • Reactive media query tracking with optimal performance
  • SSR-safe via getServerSnapshot
  • Lightweight and minimal overhead

import { useTheme } from 'styled-components'; // or from '@emotion/react'
import { useMediaQuery } from 'styled-breakpoints/use-media-query';
import { Box } from 'third-party-library';

const SomeComponent = () => {
  const theme = useTheme()
  const isMd = useMediaQuery(theme.breakpoints.only('md'));

  return <Box>{isMd && <Box />}</Box>;
};
API
Type Declarations
declare function useMediaQuery(
  query: string,
  options?: {
    getServerSnapshot: () => boolean
  }
): boolean;
Arguments
  • query
    CSS media query to evaluate.
    Accepts values with or without the @media prefix.

  • options (optional)

    • getServerSnapshot
      Function used during SSR to provide a stable boolean value for the initial render.
Returns
  • boolean
    true if the media query currently matches the viewport.


License

MIT License

This project is licensed under the MIT License - see the LICENSE file for details.



Contributors

mg901
mg901

Abu Shamsutdinov
Abu Shamsutdinov

Sova
Sova

Jussi Kinnula
Jussi Kinnula

Rafał Wyszomirski
Rafał Wyszomirski

Adrian Celczyński
Adrian Celczyński

Sam Holmes
Sam Holmes

Ontopic
Ontopic

Ryan Bell
Ryan Bell

Bart Nagel
Bart Nagel

Greg McKelvey
Greg McKelvey

Buck DeFore
Buck DeFore

Pierre Burel
Pierre Burel

Pawel Kochanek
Pawel Kochanek

Ian Christopher B. de Jesus
Ian Christopher B. de Jesus

David de Lusenet
David de Lusenet

Dan Adler
Dan Adler

Keywords