In the vertical mode<\/em>, the image is on top, and the title and paragraphs are below it.<\/p>\n We want this Card to switch between these two modes. Traditionally, we would wrap the styles around the The problem here is that Media Queries only account for the viewport size, not the container size. If the Card is placed inside a container with a width of 500px, the Card will still be in the horizontal mode, even though it’s not suitable for the container size. We may end up with the content and the image being squished, or the image overflowing the container.<\/p>\n This is one example where Container Queries can be useful. With Container Queries, we can apply styles based on the container’s size, instead of just the viewport size.<\/p>\n To use them, we will need to wrap our The When we set Now, we can apply the styles based on the container’s size in addition to the Media Queries:<\/p>\n The two cards from our example should now switch to the vertical layout when the container’s width is less than 720px, regardless of the current viewport size.<\/p>\n<\/span><\/span><\/figure>\n
@media<\/code> query, for example:<\/p>\n
\r\n.card {\r\n display: flex;\r\n gap: 4rem;\r\n}\r\n.card .featured-img {\r\n width: 40%; \r\n}\r\n.card .content {\r\n width: 60%; \r\n}\r\n\r\n@media screen and (width <= 720px) {\r\n .card {\r\n flex-direction: column;\r\n }\r\n \r\n .card .featured-img {\r\n width: 100%; \r\n }\r\n \r\n .card .content {\r\n width: 100%; \r\n }\r\n}\r\n<\/pre>\n
<\/span><\/span><\/figure>\n
.card<\/code> with a new container. In this example, we will name it
.card-container<\/code>. Then we can add it with the
container-type: inline-size<\/code> declaration.<\/p>\n
\r\n.card-container {\r\n container-type: inline-size;\r\n width: 100%;\r\n}\r\n<\/pre>\n
inline-size<\/code> value specifically enables querying the inline dimension, usually the width in horizontal writing modes of a container.<\/p>\n
container-type: inline-size<\/code> on an element, we’re essentially telling the browser to treat that element as a container whose width can be queried using Container Queries. This is required for applying styles based on the size of the container, rather than the viewport. The
width<\/code> is also important to ensure the container takes up the full width of its parent.<\/p>\n
\r\n@container (max-width: 720px) {\r\n .card {\r\n flex-direction: column;\r\n }\r\n \r\n .card .featured-img {\r\n width: 100%; \r\n }\r\n \r\n .card .content {\r\n width: 100%; \r\n }\r\n}\r\n<\/pre>\n
<\/span><\/span><\/figure>\n
Browser Compatibility<\/h4>\n