![](/img/trans.png)
[英]How can I set the width of an element in CSS to be equal to 10% of the height?
[英]How can I assign a height to an element, such that the height is equal to the height of the screen?
我有一个<section>
里面有一些内容。
<section class="Header">
<h1 class="mainHeader">Lorem ipsum dolor sit amet con</h1>
<h3 class="subHeader">obcaecati laboriosam iste ad exercitationem culpa aspernatur, molestias</h3>
</section>
我已经为Header
所有subclasses
提供了一些CSS
。 只是为了让他们看起来不错。 Header
应该是屏幕的高度。 因为在每个视口,所有subclasses
字体大小都会改变。
现在,我已经给了subHeader
margin-bottom
来制作screen
size
Header
。 但这是一种错误的做法,因为我每次都需要为每个viewport
更改subHeader
的margin-bottom
。 此外,在许多screen
sizes
,它可能比screen
更短或更长。
当我分配media query
以使网站响应时。 对于较小的屏幕尺寸,例如:(max-width: 768px) 我减小了text
的size
,并且header
向上移动,但我希望它始终是设备的height
并且即使是font-size
也不改变其height
font-size
增加或减少。
我在网上搜索并得到了一些解决方案:
第一:使用height: 100vh;
第二:通过Javascript
(下面的代码)
var vHeight = $(window).height(),
header= $('.Header');
header.css({
"height": vHeight
});
Header
的高度大于屏幕尺寸。包起来:
主要问题:如何为元素分配高度,使高度等于屏幕的高度(在查看网站时正在使用)?
有人知道怎么做吗?
要获得屏幕的高度,您可以使用Window.screen对象,您可以在其中使用多个属性,例如screen.height
和screen.width
。
例如,这会给你一个变量中的屏幕高度:
let screenHeight = window.screen.height;
现在,您可以使用该高度动态/以编程方式更改屏幕的确切高度所需的任何内容。 例如,设置元素的高度:
let yourElement = document.getElementById('elementsId');
yourElement.style.height = screenHeight;
编辑
您还可以尝试使用window.innerHeight获取视口高度,因为它基于视口的宽度:
let viewHeight = window.innerHeight;
尽管您可能需要调整一些像素,但它应该与您的媒体查询更好地配合。
使用硬编码的宽度和高度时要小心。 它们在一种屏幕尺寸上看起来很棒,但会破坏所有其他尺寸。 当响应性是一个问题时,尝试坚持使用基于百分比的大小调整并使用诸如盒模型和flexbox 之类的东西来进行布局。
这不适合你吗?
html, body { margin: 0; padding: 0; } .Header { height: 100vh; overflow: hidden; background-color: yellow; /* Just to show the area */ }
<section class="Header"> <h1 class="mainHeader">Lorem ipsum dolor sit amet con</h1> <h3 class="subHeader">obcaecati laboriosam iste ad exercitationem culpa aspernatur, molestias</h3> </section> <p>This content is after the header</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.