简体   繁体   中英

How to set an element's height relative to the screen size

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.

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%;

UPDATE 2021

you can use vh (viewport height) this will automatically adjust to they screen height

height:100vh;

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM