【发布时间】:2020-07-28 11:48:16
【问题描述】:
我有一个带有页眉的经典网站设置,带有侧边栏的主要内容和页脚。在更宽的屏幕上,我希望页眉和页脚是全宽的,而主栏和侧边栏有固定的宽度,每个站点上都有空格。当您使屏幕变窄时,空白会缩小(很像 StackExchange 中的)。一旦达到主要+侧边栏的宽度,这些就会缩小。在过去,我会在 main+sidebar 周围放置一个包装器,应用 max-width:1200px; margin:0 auto; 并完成。现在我试图用grid 解决这个问题,但无济于事。代码如下:
<div id="totalcontent">
<div id="header">content</div>
<div id="main">content</div>
<div id="sidebar">content</div>
<div id="footer">content</div>
</div>
<style>
#totalcontent {
grid-template-areas:
'header header'
'main sidebar'
'footer footer';
grid-template-columns: 66% auto;
}
</style>
现在,我可以将(比如说)max-width:900px; float:right 放在 #main 上,将 max-width:300px; float:left; 放在 #sidebar 上以使它们更窄,但只有当窗口宽度为 1800px 时,这才会导致带有 @987654330 的整齐居中的内容@ 两边的空格。一旦屏幕变窄,主边栏+侧边栏就会向左转,因为在1500px 宽度处,您需要grid-template-columns: 70% auto; 两边都有150px 空白。
我尝试了什么
- 使其成为一个四列网格,主栏和侧栏两侧都有空块。用
grid-template-columns尝试了各种事情来优先考虑缩小的空块。不走运。 - 使用媒体查询来调整
grid-template-columns。这行得通,但是在拖动窗口来调整它的大小时使设计变得跳跃。 - 放弃网格系统并恢复为 css 和添加的 html。这可行,但看起来很老套。
后一种解决方案如下所示:
<div id="totalcontent">
<div id="header">content</div>
<div id="main"><div class="inner">content</div></div>
<div id="sidebar"><div class="inner">content</div></div>
<div id="footer">content</div>
</div>
<style>
#main {width:calc( 900px + ( (98vw - 1200px) / 2) );}
#main .inner {max-width:900px; float:right}
#sidebar {width:calc( 300px + ( (98vw - 1200px) / 2) );}
#sidebar. inner {max-width:300px; float:left;}
</style>
<!-- 98vw instead of 100vw as a safety margin to account for gap -->
问题
问题似乎是您可以使用justify-content:center; 将单个网格项目居中在一行内,但您不能将多个网格项目居中在一行内。那是对的吗?如果没有,我该怎么做?
【问题讨论】:
-
justify-content 是一个与 CSS Flex 相关的属性,它基本上会影响您应用“justify-content”的项目内部的所有项目。因此,如果您在一行中有 4 个项目(例如一个 div) justify-content: center 将所有 4 个项目彼此相邻地填充在行的中心。它应与“display: flex”一起使用。
-
stackoverflow.com/questions/45536537/centering-in-css-grid 如果您想在网格设置中定位项目,这可以帮助您
-
简而言之:在网格中它称为 justify-items 而不是 justify-content
标签: html css position css-grid