使用Scss敲一个响应式网格布局
bootstarp 许多人都用过,是一个非常丰富的框架,那么,现在闲来无事,模仿 bootstrap 敲一个简单的响应式布局框架。
1. 确定响应
确立需要响应的屏幕设备宽度,仿 bootstrap 设计
- 超小屏幕的手机 576px
- 小型屏幕的平板电脑 768px
- 中型屏幕的台式电脑 992px
- 大型屏幕的台式电脑 1200px
// 需响应屏幕宽度的变量
$xs: 576px;
$sm: 768px;
$md: 992px;
$lg: 1200px;
2. 确定网格数
bootstrap 是有 12 列的网格,但我往往在开发的时候需要用到更加细致的布局,所以现在我要整个 24 列的。
$column-count: 24;
3. 设置网格 DIV 和每个列的占比
// 设置网格 DIV
.grid {
display: grid;
width: 100%;
grid-template-columns: repeat($column-count,1fr);
}
// 每个列的占比
@for $i from 1 through $column-count {
.grid-col-#{$i} {
grid-column: span $i;
width: 100%;
box-sizing: border-box;
}
}
4. 响应式设置, xs sm md lg 四个屏幕的响应式
// xs
@media (min-width: $xs) {
@for $i from 1 through $column-count {
.grid-col-xs-#{$i} {
grid-column: span $i;
}
}
}
// sm
@media (min-width: $sm) {
@for $i from 1 through $column-count {
.grid-col-sm-#{$i} {
grid-column: span $i;
}
}
}
// md
@media (min-width: $md) {
@for $i from 1 through $column-count {
.grid-col-md-#{$i} {
grid-column: span $i;
}
}
}
// lg
@media (min-width: $lg) {
@for $i from 1 through $column-count {
.grid-col-lg-#{$i} {
grid-column: span $i;
}
}
}
5. 编译并实践
使用 class
<div class="grid">
<div class="grid-col-24 grid-col-xs-20 grid-col-sm-12 grid-col-md-6 grid-col-lg-1" style="background-color: blueviolet;"></div>
<div class="grid-col-24 grid-col-xs-4 grid-col-sm-12 grid-col-md-18 grid-col-lg-23" style="background-color: red;"></div>
<div class="grid-col-24 grid-col-xs-4 grid-col-sm-12 grid-col-md-18 grid-col-lg-23" style="background-color: yellow;"></div>
<div class="grid-col-24 grid-col-xs-20 grid-col-sm-12 grid-col-md-6 grid-col-lg-1" style="background-color: blue;"></div>
</div>