[英]why 100% or 100vh height not occupying full page height
I was learning css
pseudo-selector class ::before
.我正在学习
css
伪选择器 class ::before
。 I am confused how come 100% value given to height
property of background-color
not actually occupying full page height.我很困惑为什么
background-color
的height
属性的 100% 值实际上并没有占据整个页面高度。 I tried with viewport height also.我也尝试了视口高度。 Same issue.
同样的问题。 Below is my code:
下面是我的代码:
* { margin: 0; padding: 0; }:root { --navbar-height: 59px; } #navbar { display: flex; align-items: center; border: 2px solid red; } #navbar ul { display: flex; } #navbar::before { content: ""; background-color: black; position: absolute; /* height being 100% or 100vh not occupying full page */ height: 100vh; width: 100%; z-index: -1; opacity: 0.4; } #navbar ul li { list-style: none; font-size: 1.3rem; } #navbar ul li a { display: block; padding: 3px 22px; border-radius: 20px; text-decoration: none; }
<nav id="navbar"> <ul> <li class="item"><a href="#">home</a></li> <li class="item"><a href="#">services</a></li> <li class="item"><a href="#">contactus</a></li> </ul> </nav>
output output
what I expected was black background-color
because have been given 100% height will occupy whole page.我所期望的是黑色
background-color
,因为已给出 100% 的高度将占据整个页面。 But it didn't happen.但它没有发生。 Why is it so?
为什么会这样?
The issue is due to display: flex;问题是由于 display: flex; on #navbar.
在#navbar 上。 Remove that and you should be fine.
删除它,你应该没问题。 Another solution is wrapping the navbar in a parent div and adding:: before on it.
另一种解决方案是将导航栏包装在父 div 中并在其之前添加::。
You just need to position your :before
correctly.你只需要 position 你的
:before
正确。 Add below CSS to your #navbar::before
and you should be set:将下面的 CSS 添加到您的
#navbar::before
,您应该设置:
top: 0;
left: 0;
Because your positioning is absolute you need to check the top and left properties.因为您的定位是绝对的,所以您需要检查 top 和 left 属性。
I replicated your code and then opened the chrome dev tools as shown in the attached screenshot.我复制了您的代码,然后打开了 chrome 开发工具,如随附的屏幕截图所示。 If you open the computed tab you will see that the top property is -516.378px.
如果打开计算选项卡,您将看到 top 属性为 -516.378px。
You can do this by clicking Elements>Computed which will show you all the properties after the browser has calculated them.您可以通过单击 Elements>Computed 来执行此操作,这将在浏览器计算出所有属性后显示给您。
If you add top: 0;如果添加顶部:0; as shown below you can override the calculated css position.
如下所示,您可以覆盖计算的 css position。
#navbar::before {
content: "";
background-color: black;
position: absolute;
/* height being 100% or 100vh not occupying full page */
height: 100vh;
width: 100%;
top: 0;
z-index: -1;
opacity: 0.4;
}
Here's a stackblitz example you can play with to try it out yourself:这是一个 stackblitz 示例,您可以自己尝试一下:
https://stackblitz.com/edit/js-82vdk5?file=style.css https://stackblitz.com/edit/js-82vdk5?file=style.css
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.