<div class="parent">
<div class="line"></div>
<p>Parent (window) width: <span class="window"></span></p>
<div class="line"></div>
</div>
<h1><code>CSS min() function<a class="support" href="https://caniuse.com/#feat=mdn-css_types_min">?</a></code></h1>
<p><code class="value">width: min(<span class="max">50%</span>, <span class="min">400px</span>);</code></p>
<div class="element">
<p>Element actual width: <span class="actual"></span></p>
</div>
xxxxxxxxxx
body {
display: grid;
place-content: center;
text-align: center;
font-family: system-ui, serif;
font-size: 24px;
}
.value {
background: lavenderblush;
border-radius: 20px;
padding: 0.3em 0.75em;
}
.window,
.actual {
font-family: monospace;
padding: 0.15em 0.35em;
}
.element {
background-color: papayawhip;
height: 200px;
width: min(50vw, 400px);
display: grid;
place-content: center;
justify-self: center;
border: 1px solid gold;
}
.actual {
background: gold;
}
.window {
background: lavenderblush;
border-bottom: 3px dashed goldenrod;
}
.highlight {
background-color: gold;
border-bottom: 3px dashed goldenrod;
}
h1 {
font-weight: 300;
margin: 0 0 1rem;
}
.support {
color: initial;
background: papayawhip;
border: 1px solid gold;
width: 2.5rem;
height: 2.5rem;
font-size: 2rem;
display: inline-grid;
place-content: center;
border-radius: 50%;
vertical-align: text-top;
text-decoration: none;
margin-left: 0.25rem;
}
.parent {
font-size: 16px;
width: 100vw;
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
}
.line {
height: 1px;
width: 100%;
background-color: lightgray;
}
.parent p {
background: #f9f9f9;
border: 1px solid lightgray;
padding: 1rem;
}
xxxxxxxxxx
const updateValues = () => {
let pageWidth = window.innerWidth;
let elemWidth = document.querySelector('.element').clientWidth;
document.querySelector('.window').innerText = pageWidth + 'px';
document.querySelector('.actual').innerText = elemWidth +'px';
checkWidth(elemWidth);
}
const checkWidth = (elemWidth) => {
const minVal = parseInt(document.querySelector('.min').innerText, 10);
if (elemWidth < minVal) {
document.querySelector('.min').classList.remove('highlight');
document.querySelector('.max').classList.add('highlight');
} else {
document.querySelector('.max').classList.remove('highlight');
document.querySelector('.min').classList.add('highlight');
}
}
updateValues();
window.onresize = updateValues;
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.