admin管理员组文章数量:1355570
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.
- 1 stackoverflow./help/how-to-ask – Mister Jojo Commented May 3, 2020 at 23:22
2 Answers
Reset to default 5the %
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>
本文标签: javascriptHow to set an element39s height relative to the screen sizeStack Overflow
版权声明:本文标题:javascript - How to set an element's height relative to the screen size - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743986372a2571342.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论