But, what about the size of the element itself?
First, figure out what size the element will be in a given responsive layout.
Then use multiple MQs to toggle CSS changes on & off.
.widget {
/* narrow 1col layout: narrow version CSS */
}
@media (min-width: 480px) and (max-width: 959px) {
.widget {
/* wide 1col layout: wide version CSS */
}
}
@media (min-width: 960px) and (max-width: 1199px) {
.widget {
/* narrow 2col layout: narrow version CSS */
}
}
@media (min-width: 1200px) {
.widget {
/* wide 2col layout: wide version CSS */
}
}
<main class="page-content">
<div class="widget"></div>
</main>
<aside class="page-sidebar">
<div class="widget"></div>
</aside>
flex-wrap
& flex-basis
adjust layout depending on container size.parent {
--container-width: 720px;
display: flex;
flex-wrap: wrap;
}
.child {
flex-grow: 1;
flex-basis: calc((var(--container-width) - 100%) * 999);
}
.grid {
display: grid;
grid-template-columns:
repeat(auto-fit, minmax(200px, 1fr));
}
font-size
, etcclamp()
function (optionally with min()
& max()
) to create responsive font-size
, line-height
, etc.ResizeObserver
const ro = new ResizeObserver(entries => {
for (let e of entries) {
const size = Array.isArray(e.borderBoxSize)
? e.borderBoxSize[0]
: e.borderBoxSize;
const action = (size.inlineSize >= 480)
? 'add'
: 'remove';
e.target.classList[action]('wide');
}
});
ro.observe(document.getElementById('box'));
Resize Observer is supported in all modern browsers (but not IE & pre-Chromium Edge), covering 92.2% of global usage.
ResizeObserver
polyfillro.observe(el)
ro.unobserve(el)
.element {
width: 400px;
}
.element:query(min-width: 300px) {
width: 200px;
}
.page-content,
.page-sidebar {
container: size layout style;
container-type: inline-size;
}
Disables content-based sizing
* Spec still in WIP
.widget {
/* narrow container: narrow version CSS */
}
@container (min-width: 480px) {
.widget {
/* wide container: wide version CSS */
}
}
Each .widget
queries its potential containers.
.page-content {
container-name: main;
}
.page-content__gallery {
container-name: gallery;
}
@container main (min-width: 480px) {
.widget { /* wide `main` container */ }
}
@container gallery (min-width: 480px) {
.widget { /* wide `gallery` container */ }
}
Chrome ... Canary ... behind a flag
jdsteinbach