[{"id":378111,"date":"2024-06-10T09:12:50","date_gmt":"2024-06-10T16:12:50","guid":{"rendered":"https:\/\/css-tricks.com\/?p=378111"},"modified":"2024-06-14T08:31:04","modified_gmt":"2024-06-14T15:31:04","slug":"css-container-queries","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/css-container-queries\/","title":{"rendered":"CSS Container Queries"},"content":{"rendered":"\n
\n
\n

Container queries are often considered a modern approach to responsive web design where traditional media queries have long been the gold standard \u2014 the reason being that we can create layouts made with elements that respond to, say, the width of their containers<\/em> rather than the width of the viewport<\/em>.<\/p>\n\n\n\n

.parent {\n  container-name: hero-banner;\n  container-type: inline-size;\n\n  \/* or container: hero-banner \/ inline-size; *\/\n}\n\n}\n\n.child {\n  display: flex;\n  flex-direction: column;\n}\n\n\/* When the container is greater than 60 characters... *\/\n@container hero-banner (width > 60ch) {\n  \/* Change the flex direction of the .child element. *\/\n  .child { \n    flex-direction: row;\n  }\n}<\/code><\/pre>\n<\/div>\n\n\n\n

Why care about CSS Container Queries?<\/h2>\n\n\n
    \n
  1. When using a container query, we give elements the ability to change based on their container’s size<\/em>, not the viewport.<\/li>\n<\/ol>\n\n\n\n
      \n
    1. They allow us to define all of the styles for a particular element in a more predictable<\/em> way.<\/li>\n<\/ol>\n\n\n\n
        \n
      1. They are more reusable<\/em> than media queries in that they behave the same no matter where they are used. So, if you were to create a component that includes a container query, you could easily drop it into another project and it will still behave in the same predictable fashion.<\/li>\n<\/ol>\n\n\n\n
          \n
        1. They introduce new types of CSS length units<\/em> that can be used to size elements by their container’s size.<\/li>\n<\/ol>\n<\/div>\n<\/div>\n\n\n\n
          <\/div>\n\n\n