DIV高度设置为屏幕的百分比吗?


74

我希望将父DIV设置为整个100%屏幕高度的70%。我已经设置了以下CSS,但是它似乎什么也没做:

body {
font-family: 'Noto Sans', sans-serif;
margin: 0 auto;
height: 100%;
width: 100%;
}
.header {
height: 70%;
}

由于某种原因,它似乎无法正常工作,并且标题不是屏幕尺寸的70%。有什么建议吗?

Answers:



8

这是解决方案

html还要添加到100%

html,body {

   height: 100%;
   width: 100%;

}


1

如果要基于屏幕高度而不是窗口高度:

const height = 0.7 * screen.height

// jQuery
$('.header').height(height)

// Vanilla JS
document.querySelector('.header').style.height = height + 'px'

// If you have multiple <div class="header"> elements
document.querySelectorAll('.header').forEach(function(node) {
  node.style.height = height + 'px'
})

0

通过使用绝对定位,您可以使<body><form><div>适合您的浏览器页面。例如:

<body style="position: absolute; bottom: 0px; top: 0px; left: 0px; right: 0px;">

然后简单地把<div>它里面和使用的任何百分比,无论是height或者width你希望

<div id="divContainer" style="height: 100%;">
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.