Reputation: 41
I want to set the height
of an element as a percentage of the full-screen mode's dimensions so that when the browser window is smaller, the height does not change.
Upvotes: 4
Views: 7905
Reputation: 4067
the %
operator is dynamic it changes according to the width or height of the screen
so if you want that the length may not change you can use px
or pt
or even rem
(but it depends on root elements size)
height:100%;
you can use vh
(viewport height) this will automatically adjust to they screen height
height:100vh;
Upvotes: 5
Reputation: 21171
You could specify the height
in vh
, which equates to 1% of the height of the viewport's (not the screen's) initial containing block.
If you actually need the height
to be relative to the screen height, then you would have to use JavaScript's screen
object:
window.screen.height;
window.screen.width;
You can use these values directly in an style
attribute:
// 10% of the screen height:
document.getElementById('container')
.style.height = `${ window.screen.height * 0.1 }px`;
#container {
width: 100%;
border-bottom: 3px solid black;
/* Fallback value (relative to viewport, not screen) */
height: 10vh;
}
<div id="container"></div>
Or create something more reusable using calc()
and CSS custom properties:
document.documentElement.style.setProperty(
'--container-height', `${ window.screen.height }px`);
document.documentElement.style.setProperty(
'--container-width', `${ window.screen.width }px`);
:root {
/* We use thew viewport's dimensions as fallback values: */
--screen-height: 100vh;
--screen-width: 100vw;
}
#container {
width: 100%;
border-bottom: 3px solid black;
/* 10% of the screen height: */
height: calc(0.1 * var(--container-height));
}
<div id="container"></div>
Upvotes: 2