我正在尝试创建一个相当简单的网站布局,但是对于CSS Grid来说,这是我的新手,我敢肯定我会以错误的方式进行操作。
body{
margin: 0;
padding: 0;
}
.container {
display: grid;
grid-template-columns: 1fr 3fr 1fr;
grid-template-rows: 120px 450px;
}
.header,
.main {
border: 1px solid black;
}
.side {
background-color: antiquewhite;
border-bottom: 1px solid black;
}
<div class="container">
<div class="side">Should have the same background color/gradient as header</div>
<header class="header">Header</header>
<div class="side">Should have the same background color/gradient as header</div>
<div class="side">Should have the same background color/gradient as Content</div>
<main class="main">Content</main>
<div class="side">Should have the same background color/gradient as Content</div>
</div>
这就是我想要的:一个标题和一个主要部分,两者的内容都保留在页面的中心-但同时我希望这两行的整体都有自己的背景颜色。但是我的解决方案使用了一堆不必要的div,并且grid-template-rows: 150px 450px;
的使用也是错误的,因为我希望内容占据页面的其余部分而不是450px。
我该如何实现?
答案 0 :(得分:1)
尝试为容器类提供最大宽度和边距
.container{
max-width:calc( (3/5) * 100vw);
margin:0 auto;
grid-template-rows: 120px 1fr;
display:grid;
}
答案 1 :(得分:0)
您可以这样简化:
body {
margin: 0;
padding: 0;
display: grid;
grid-template-columns: 1fr 3fr 1fr;
min-height:100vh;
background:
linear-gradient(red, blue) top/100% 120px no-repeat,
linear-gradient(green, grey) bottom/100% calc(100% - 120px) no-repeat;
}
body:before,
body:after{
content:"";
}
.container {
display: grid;
grid-template-rows: 120px 1fr;
}
.header,
.main {
border: 1px solid black;
}
<div class="container">
<header class="header">Header</header>
<main class="main">Content</main>
</div>
如果这是您体内唯一的内容,则还可以使用max-width
和vw
单位,如下所示:
body {
margin: 0;
padding: 0;
background:
linear-gradient(red, blue) top/100% 120px no-repeat, /*Cover the header*/
linear-gradient(green, grey) bottom/100% calc(100% - 120px) no-repeat; /*Cover the content*/
}
.container {
/* you want 1f 3fr 1fr so we have 5fr so we need (3/5)*/
max-width:calc( (3/5) * 100vw);
margin:auto;
display: grid;
grid-template-rows: 120px 1fr;
min-height:100vh;
}
.header,
.main {
border: 1px solid black;
}
<div class="container">
<header class="header">Header</header>
<main class="main">Content</main>
</div>
答案 2 :(得分:0)
尝试这个:
body {
margin: 0;
padding: 0;
}
div.container {
display: grid;
grid-template-columns: 1fr 3fr 1fr;
grid-template-rows: 150px; 1fr;
height: 100vh;
}
.header-container, .content-container {
display: contents;
}
.header-container div {
background: #ddd;
}
.content-container div {
background: #aaa;
}
<body>
<div class="container">
<div class='header-container'>
<div class='side'>Side</div>
<div class='header'>Header</div>
<div class='side'>Side</div>
</div>
<div class='content-container'>
<div class='side'>Side</div>
<div class='content'>Content</div>
<div class='side'>Side</div>
</div>
</div>
</body>