Components that must be both reusable and responsive tend to break down once other components are nested inside them. A parent's media query ends up restating styling that the child already knows how to apply. Take a <CTA /> component: on smaller screens it needs to stack and stretch its button to full width. With flexbox, a media query that flips the flex direction and widens the button does the job — until the button is itself a component with a prop that already makes it full-width.

The parent has now duplicated the button's own styling. Multiply that across a codebase and changing how full-width buttons look means hunting the change down in every place it was copied. The fix is to stop reaching for media queries and instead drive styling through the props components already have, passing different values as the viewport changes. CSS container queries can address part of this, but they are still in early days and don't solve the problem of passing a variety of props based on screen width.

Watching the viewport

The first step is tracking the current page width and resolving it to a breakpoint. Any front-end framework can do this; the example uses a Vue composable, with numeric values for the currentBreakpoint object — why numbers matter becomes clear below.

// composables/useBreakpoints.js

import { readonly, ref } from "vue";

const bps = ref({ xs: 0, sm: 1, md: 2, lg: 3, xl: 4 })
const currentBreakpoint = ref(bps.xl);

export default () => {
  const updateBreakpoint = () => {
  
    const windowWidth = window.innerWidth;
    
    if(windowWidth >= 1200) {
      currentBreakpoint.value = bps.xl
    } else if(windowWidth >= 992) {
      currentBreakpoint.value = bps.lg
    } else if(windowWidth >= 768) {
      currentBreakpoint.value = bps.md
    } else if(windowWidth >= 576) {
      currentBreakpoint.value = bps.sm
    } else {
      currentBreakpoint.value = bps.xs
    }
  }

  return {
    currentBreakpoint: readonly(currentBreakpoint),
    bps: readonly(bps),
    updateBreakpoint,
  };
};

The resize listener is wired up in the main App.vue file, with the caveat that it should probably be debounced (omitted here for brevity).

// App.vue

<script>
import useBreakpoints from "@/composables/useBreakpoints";
import { onMounted, onUnmounted } from 'vue'

export default {
  name: 'App',
  
  setup() {
    const { updateBreakpoint } = useBreakpoints()

    onMounted(() => {
      updateBreakpoint();
      window.addEventListener('resize', updateBreakpoint)
    })

    onUnmounted(() => {
      window.removeEventListener('resize', updateBreakpoint)
    })
  }
}
</script>

Mode-based styling

The <CTA /> component gains a styling prop whose mode names are entirely arbitrary. The parent maps the current breakpoint to a mode:

// CTA.vue
props: {
  displayMode: {
    type: String,
    default: "default"
  }
}
<CTA :display-mode="currentBreakpoint > bps.md ? 'default' : 'compact'" />

This is where the numeric breakpoints pay off: a single number can select the correct mode for everything below or above a threshold. The component then applies classes according to the mode it receives.

// components/CTA.vue

<template>
  <div class="cta" :class="displayMode">
    
    <div class="cta-content">
      <h5>title</h5>
      <p>description</p>
    </div>
    
    <Btn :block="displayMode === 'compact'">Continue</Btn>
    
  </div>
</template>

<script>
import Btn from "@/components/ui/Btn";
export default {
  name: "CTA",
  components: { Btn },
  props: {
    displayMode: {
      type: String,
      default: "default"
    },
  }
}
</script>

<style scoped lang="scss">
.cta {
  display: flex;
  align-items: center;
  
  .cta-content {
    margin-right: 2rem;
  }

  &.compact {
    flex-direction: column;
    .cta-content {
      margin-right: 0;
      margin-bottom: 2rem;
    }
  }
}
</style>

Media queries are no longer needed for this. Applied across many components, the technique improves UI consistency and stability while shrinking the total code written — though for a single simple component it is admittedly more work.

Per-breakpoint modes and reuse

Driving responsive styling from JavaScript and CSS classes also makes two harder cases tractable. One is reverting a component to an earlier mode at larger sizes — say, small mode at 50% width until a resize event should make it full-width. The other is using the same component in different modes on different pages, something frameworks like Bootstrap and Tailwind don't support; a media query limited to middle screen sizes still wouldn't let props vary by width. (Those frameworks remain usable with this approach — just without their responsive classes.)

Showing three versions of a call-to-action components with nested components within it.

To get there, allow a custom mode per breakpoint by passing an array whose first item corresponds to the smallest screen. The props are extended accordingly:

<CTA :custom-mode="['compact', 'default', 'compact']" />
props: {
  displayMode: {
    type: String,
    default: "default"
  },
  customMode: {
    type: [Boolean, Array],
    default: false
  },
}
import { computed } from "vue";
import useBreakpoints from "@/composables/useBreakpoints";

// ...

setup(props) {

  const { currentBreakpoint } = useBreakpoints()

  const mode = computed(() => {
    if(props.customMode) {
      return props.customMode[currentBreakpoint.value] ?? props.displayMode
    }
    return props.displayMode
  })

  return { mode }
},

This picks the mode from the array by current breakpoint and falls back to displayMode when none is found; mode is then what styles the component.

Pulling the shared logic out

The logic for resolving the correct mode can be extracted into its own composable.

// composables/useResponsive.js

import { computed } from "vue";
import useBreakpoints from "@/composables/useBreakpoints";

export const useResponsive = (props) => {

  const { currentBreakpoint } = useBreakpoints()

  const mode = computed(() => {
    if(props.customMode) {
      return props.customMode[currentBreakpoint.value] ?? props.displayMode
    }
    return props.displayMode
  })

  return { mode }
}

Props can be extracted the same way. Vue 2 mixins repeated props but carried noticeable drawbacks; Vue 3 merges them with a component's other props through the composable. The caveat: IDEs generally can't autocomplete props defined this way, so a mixin is an option if that's too disruptive. A custom validator can optionally restrict each component to its own available modes, with the first value passed in as the default.

// composables/useResponsive.js

// ...

export const withResponsiveProps = (validation, props) => {
  return {
    displayMode: {
      type: String,
      default: validation[0],
      validator: function (value) {
        return validation.indexOf(value) !== -1
      }
    },
    customMode: {
      type: [Boolean, Array],
      default: false,
      validator: function (value) {
        return value ? value.every(mode => validation.includes(mode)) : true
      }
    },
    ...props
  }
}
// components/CTA.vue

import Btn from "@/components/ui/Btn";
import { useResponsive, withResponsiveProps } from "@/composables/useResponsive";

export default {
  name: "CTA",
  components: { Btn },
  props: withResponsiveProps(['default 'compact'], {
    extraPropExample: {
      type: String,
    },
  }),
  
  setup(props) {
    const { mode } = useResponsive(props)
    return { mode }
  }
}