全局class说明
.grid {
display: grid;
}
.flex {
display: flex;
}
.item {
height: 100px;
}
水平垂直居中
Grid实现
<section class="center container grid">Grid 水平垂直居中</section>
justify-content: center; // 或justify-items: center;
align-items: center;
Flex实现
<section class="center container flex">Flex 水平垂直居中</section>
.flex.center {
justify-content: center;
align-items: center;
}
两栏(左侧固定宽度,右侧自适应)
Grid实现
<section class="items container grid">
<div class="item">左栏</div>
<div class="item">右栏</div>
</section>
.grid.items {
grid-template: 1fr / 100px 1fr;
height: 100px;
.item {
&:nth-of-type(1) {
background: olive;
}
&:nth-of-type(2) {
background: aquamarine;
}
}
}
Flex实现
<section class="items container flex">
<div class="item">左栏</div>
<div class="item">右栏</div>
</section>
.flex.items {
.item {
&:nth-of-type(1) {
flex: 0 0 100px;
background: olive;
}
&:nth-of-type(2) {
flex: 1 1 auto;
background: aquamarine;
}
}
}
双飞翼
Grid实现
<section class="three-columns container grid">
<div class="item center">center</div>
<div class="item left">left</div>
<div class="item right">right</div>
</section>
.grid.three-columns {
grid-template-columns: 100px 1fr 100px;
grid-template-areas: "left center right";
.item {
height: 100px;
&.center {
grid-area: center;
background: olive;
}
&.left {
// order: -1; // 也支持order,则不用再使用grid-template-areas
background: aquamarine;
}
&.right {
background: darkcyan;
}
}
}
Flex实现
<section class="three-columns container flex">
<div class="item center">center</div>
<div class="item left">left</div>
<div class="item right">right</div>
</section>
.flex.three-columns {
.item {
height: 100px;
&.center {
flex: 1 1 auto;
order: 1;
background: olive;
}
&.left {
flex: 0 0 100px;
background: aquamarine;
}
&.right {
flex: 0 0 100px;
order: 2;
background: darkcyan;
}
}
}
stick-footer
css3之前的
stick footer
布局的写法十分晦涩难懂,现在使用Grid、Flex就十分简单啦
Grid实现
<section class="stick-footer container grid">
<h2>sticker</h2>
<main>
<li>content</li>
</main>
<button>footer</button>
</section>
.grid.stick-footer {
grid-template-rows: auto 1fr auto;
min-height: 200px;
li {
line-height: 2;
}
}
- content内容比较少时,footer就固定在底部
- 多复制几条
li
,footer就会贴在main
的下面 - 通常满屏场景比较多,设置
min-height: 100vh
Flex实现
<section class="stick-footer container flex">
<h2>sticker</h2>
<main>
<li>content</li>
</main>
<button>footer</button>
</section>
.flex.stick-footer {
flex-direction: column;
min-height: 200px;
main {
flex: 1 1 auto;
}
}