How to use scss to develop responsive pages
2023-10-12
As we all know, page style is controlled by CSS, scss is an extension of CSS and provides a more powerful future, such as functions, etc. Later we will use the function future.
Most of the time, our pages only run on one device, web, mobile or desktop, but what do we do if we want to run on two devices at the same time? Responsiveness means writing code to match different platforms
Now , we have learned scss and responsive, let me think about what we want ?
let us get started!!
/* different media size */
$s: 375px;
$m: 768px;
$l: 1024px;
$xl: 1280px;
/* responsive function */
@mixin responsive($width-list) {
@each $width in $width-list {
@if $width == $s {
// 320 ~ 767 mobile
@media only screen and (max-width: ($m - 1px)) {
@content;
}
} @else if $width == $m {
// 768 ~ 1023 tablet ipad
@media only screen and (min-width: $m) and (max-width: ($l - 1px)) {
@content;
}
} @else if $width == $l {
// 1024 - 1279 desktop
@media only screen and (min-width: $l) and (max-width: ($xl - 1px)) {
@content;
}
} @else {
// > 1280 PC
@media only screen and (min-width: $xl) {
@content;
}
}
}
}
For example, there has two div box, boxA,boxB, it should arrange vertically on mobile and horizontally on desktop.
// in react jsx file
import style from "./index.scss";
<div className={style.box}>
<div className={style.boxA}></div>
<div className={style.boxB}></div>
</div>;
// index.scss
@import "./responsive.scss";
.box {
display: flex;
@include responsive(($s, $m)) {
flex-direction: column;
}
}
That is it, that is how to use scss to develop responsive pages .