这篇文章给大家分享的CSS布局的实现,下文介绍了10种常见的现代css布局。小编觉得挺实用的,因此分享给大家做个参考,文中示例代码介绍的非常详细,感兴趣的朋友接下来一起跟随小编看看吧。
01. 超级居中
在没有 flex 和 grid 之前,垂直居中一直不能很优雅的实现。而现在,我们可以结合 grid 和 place-items 优雅的同时实现 水平居中 和 垂直居中 。
<div class="parent blue" >
<div class="box coral" contenteditable>
🙂
</div>
.ex1 .parent {
display: grid;
place-items: center;
}
02. 可解构的自适应布局(The Deconstructed Pancake)
flex: 0 1 <baseWidth>
这种布局经常出现在电商网站:
在 viewport 足够的时候,三个 box 固定宽度横放
在 viewport 不够的时候(比如在 mobile 上面),宽度仍然固定,但是自动解构(原谅我的中文水平),不在同一水平面上
<div class="parent white">
<div class="box green">1</div>
<div class="box green">2</div>
<div class="box green">3</div>
</div>
.ex2 .parent {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.ex2 .box {
flex: 1 1 150px; /* flex-grow: 1 ,表示自动延展到最大宽度 */
flex: 0 1 150px; /* No stretching: */
margin: 5px;
}
03. 经典的 sidebar
grid-template-columns: minmax(<min>, <max>) …
同样使用 grid layout,可以结合 minmax() 实现弹性的 sidebar(这在你要适应大屏幕的时候很有用)。 minmax(<min>, <max>) 就是字面意思。结合 <flex> 单位,非常优雅,避免了数学计算宽度等不灵活的手段(比如我们设置 gap 的时候)。
<div class="parent">
<div class="section yellow" contenteditable>
Min: 150px / Max: 25%
</div>
<div class="section purple" contenteditable>
This element takes the second grid position (1fr), meaning
it takes up the rest of the remaining space.
</div>
</div>
.ex3 .parent {
display: grid;
grid-template-columns: minmax(150px, 25%) 1fr;
}