<h1 class='title'>clamp() example</h1>
<div class='container'>
<p class='resize'>Resize the viewport and watch the width change</p>
<div class='viewport-container'><p class="viewport"></p></div>
<div class="rect">
<p class='width'></p>
</div>
<p class="clamp">width: clamp(250px, 50vw, 600px);</p>
</div>
* {
box-sizing: border-box;
font-family: Inconsolata, sans-serif;
}
.title {
background-color: #20B2AA;
color: #FFFFE0;
font-size: 40px;
width: calc(100vw - 24px);
height: fit-content(10vh);
text-align: center;
padding: 12px;
margin: 0;
}
.container {
background-color: #e0d4fc;
height: 88vh;
width: calc(100vw - 24px);
padding: 12px;
display: flex;
flex-direction: column;
align-items: center;
}
.rect {
background-color: #2c35e8;
color: #FFFFE0;
width: clamp(250px, 50vw, 600px);
height: 150px;
font-weight: normal;
display: flex;
align-items: center;
justify-content: center;
margin: 20px;
}
.width {
font-size: 30px;
}
.clamp {
font-size: 30px;
color: #2c35e8;
}
.viewport-container {
padding: 6px 12px;
font-size: 20px;
}
.viewport {
color: #004f5e;
font-size: 30px;
}
.resize {
font-size: 20px;
}
const rect = document.querySelector('.rect')
const text = document.querySelector('.width')
const viewport = document.querySelector('.viewport')
const rectStyle = window.getComputedStyle(rect)
const state = {
calculate() {
this.width = parseInt(rectStyle.width).toFixed(0)
text.textContent = `width: ${this.width}px`
this.viewport = window.innerWidth
viewport.textContent = `viewport: ${this.viewport}px`
},
width: '',
viewport: ''
}
state.calculate()
window.addEventListener('resize', function(){
state.calculate()
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.