首页 > 解决方案 > 为什么 vh 有效而 % 无效?(高度CSS)

问题描述

我有一个非常简单的代码,这个特殊问题经常发生在我身上。我不明白为什么 % 不会改变高度,只有 vh 会。相反,width 没有这个问题,我可以用 %.

这是应用程序组件:

import MainPage from "./MainPage/MainPage";
import Headline from "./Headline/Headline";
import "./App.css";

function App() {
  return (
    <div className="App">
      <Headline />
      <MainPage />
    </div>
  );
}

及其CSS:

.App {
  height: 100%;
  width: 100%;
  text-align: center;
  background-color: white;
  display: flex;
  flex-direction: column;
}

这是标题组件。在这里您可以看到问题:

import "./Headline.css";

function Headline() {
  return (
    <div className="headline-container">
      <div className="headline">Cryprocurrency Tracker</div>
    </div>
  );
}

这是 Headline 的 css:

.headline-container {
  height: 10vh;      --------> % doesn't work, I can change the height only with vh.
  width: 100%;       --------> width however doesn't have this problem at all.
  background-color: #0060ff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  color: white;
  font-size: 30px;
  font-weight: 800;
  font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
}

.headline {
  height: 100%;
  width: 90%;
  display: flex;
}

编辑:这是索引 css 以防万一。索引中只有一个子组件,它是应用程序:

body {
  height: 100vh;
  width: 100vw;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
}

标签: htmlcssreactjsflexboxstyling

解决方案


百分比 (%) 是一个相对单位,因此生成的高度取决于父元素的高度。

例如,如果您考虑以下示例,则 .container div 有两个父元素:the 和 element。而且我们都知道height属性的默认值是auto,所以如果我们把和元素的高度也设置为100%,那么容器div的结果高度就等于浏览器窗口的100%高度。

资源

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Set DIV Height to 100% Using CSS</title>
<style>
    html, body {
        height: 100%;
        margin: 0px;
    }
    .container {
        height: 100%;
        background: #f0e68c;
    }
</style>
</head>
<body>
    <div class="container">The height of this DIV element is equal to the 100% height of its parent element's height.</div>
</body>
</html>


推荐阅读