CSS 中的网格设置?

Grid setup in CSS?

我是 CSS 和 HTML 的新手,在 CSS 中设置了 div,类似这样:

#topBar {
  margin-top: 0;
  height: 100px;
  width: 100%
}

#sideBar {
  width: 50px;
  margin-left: 0;
  margin-top: 100px;
  height: 100%;
}

#main {
  margin-left: 50px;
  margin-top: 100px;
  margin-bottom: 50px;
}

#footer {
  margin-bottom: 0;
  width: 100%;
}
<div id="container">
  <div id="topbar" />
  <div id="sidebar" />
  <div id="main" />
  <div id="footer" />
</div>

但这看起来一点也不像我想要的那样。它为每个 div 留下 space,即使它们的 space 被限制为 x 宽度和 x 高度。

如何设置 divs 以达到所需的效果?即在 CSS?

中有页脚、主要、侧边栏和顶部栏

CSS 实际上已经内置了您可以使用的网格“生成器”。不久前我在做类似的事情,结果是这样的:

#container {
    display: grid; //uses grid
    height: 100vh; // vh and vw is percentages of the screens width and height, nice for scaling for different devices
    width: 100vw;
    grid-template-columns: 1fr 9fr; // sets how big columns are, this sets the column quantity to two, and the first one gets 1 fraction of the are, and column two gets 9 fractions. 1fr is for sidebar
    grid-template-rows: 1.5fr 15fr 3fr; // Same as with column, but this includes footer, so 1.5 fraction goes to top bar, 15 fractions to sidebar and main area, and 3 fractions to footer
    grid-template-areas:
    "header header" // sets area to use, the same area given space in above lines. They can be directly referenced in other parts of the css documents.
    "navbar main"
    "footer footer";
}

#topbar {
    grid-area: header; // Referencing previous made areas
    display: flex; // I used this to make the top bar, as this would align the items in the bar horizontally with same amount of space between
    justify-content: space-between;
    align-items: center; //used this to center items vertically
}

#sidebar {
    grid-area: sidebar;
    text-align: center; // used this to align the text center horizontally
}

#main {
    grid-area: main;
}

#footer {
    grid-area: footer;
}

您应该使用 headernavasidefootermain 等语义标签。

然后将网格直接应用于主体元素,而不是将它们包装在额外的容器中:

body {
  margin: 0; /* removes default amrgin */
  display: grid; /* uses grid */
  min-height: 100vh; /* will expend the grid to the entire viewport */
  grid-template-columns: 1fr 2fr; /* sets the column width and ammount */
  grid-template-rows: min-content auto min-content; /* sets the row height to push the footer at the bottom and let the mian fill the rest */
  gap: 5px; /* placing the items apart */
}

header,
footer {
  grid-column: 1 / -1; /* letting those element span the entire row */
}

/* for styling purpose only */
header,
aside,
main,
footer {
  border: 2px dashed red; 
  display: flex; 
  justify-content: center;
  align-items: center;  
  padding: 10px;
}
<header>Topbar</header>
<aside>Sidebar</aside>
<main>Main</main>
<footer>Footer</footer>