SCSS câu lệnh @if @else
- SCSS câu lệnh
@if @elserất tiện lợi để thiết lập sẵn bộ template dùng chung cho nhiều vị trí. - Nội dung bài học này sẽ giúp bạn tạo sẵn một vài bộ
@if @elsehữu ích cho template của bạn.
Ví dụ về SCSS @if @else
Mẫu dành cho position
- Ta sẽ thử xây dựng một
@mixincủa thuộc tínhposition, sẽ xác định theo tên vị trí$pos, và giá trị trục$yvà trục$xtương ứng.
| SCSS | CSS |
|---|---|
@mixin position($pos,$y,$x) { position: absolute; @if $pos == 'tl' { left: $x; top: $y; }@else if $pos == 'tr' { right: $x; top: $y; }@else if $pos == 'bl' { left: $x; bottom: $y; }@else if $pos == 'br' { right: $x; bottom: $y; } } #main { position: relative; .box01 { @include position('tl',20px,40px) } .box02 { @include position('bl',50px,30px) } } |
#main {
position: relative;
}
#main .box01 {
position: absolute;
left: 40px;
top: 20px;
}
#main .box02 {
position: absolute;
left: 30px;
bottom: 50px;
}
|
'tl': top left'tr': top right'bl': bottom left'br': bottom right
Ta thấy các với các giá trị khai báo vị trí như trên ta có thể sử dụng rất gọn thuộc tính position.
Mẫu dành cho border-position
- Ta sẽ thử xây dựng một
@mixinkhác của thuộc tínhborder-radiusvới các góc xác định theo theo tên vị trí$pos, và giá trị bo góc$raidus.
| SCSS | CSS |
|---|---|
@mixin bdr-position($pos,$radius) { border-radius: 0; @if $pos == 'top' { border-#{$pos}-left-radius: $radius; border-#{$pos}-right-radius: $radius; }@else if $pos == 'bottom' { border-#{$pos}-left-radius: $radius; border-#{$pos}-right-radius: $radius; }@else if $pos == 'right' { border-bottom-#{$pos}-radius: $radius; border-top-#{$pos}-radius: $radius; }@else if $pos == 'left' { border-bottom-#{$pos}-radius: $radius; border-top-#{$pos}-radius: $radius; } } #main { @include bdr-position(top,4px) } |
#main {
border-radius: 0;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
|
Với các giá trị khai báo vị trí như trên ta có thể border góc cho thành phần rất dễ.
- Bên trên là 2 ví dụ mẫu dựng sẵn, các bạn tự khám phá thêm nhé.

