最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set an element's height relative to the screen size - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited May 3, 2020 at 23:46 Danziger 21.2k6 gold badges58 silver badges89 bronze badges asked May 3, 2020 at 23:19 AnthonAnthon 411 silver badge2 bronze badges 1
  • 1 stackoverflow./help/how-to-ask – Mister Jojo Commented May 3, 2020 at 23:22
Add a ment  | 

2 Answers 2

Reset to default 5

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>

发布评论

评论列表(0)

  1. 暂无评论