Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS Optimize Borders Into one line of Code

Tags:

css

sass

I am not sure if this is possible or not. But I feel like there should be a way to do this. I am using SASS and I am trying to find a way to optimize borders. I would like to be able to define my border sides sizes, type, and color all in one line.

There are instances where I have 1,2, or 3 borders. And what I would like to do is. Write something using SASS where all properties can be defined in one line. The problem is..

border-left: border-right: border-top: and border-bottom:

Are all separate selectors and I would like to combine them.

What I am thinking of doing is something like this...

SUDO CODE:

border ($top,$left,$right,$bottom, $type, $color);

#div {
    @include border(1px, 1px, 1px, 0, solid, #CCC);
}

I was thinking something along these lines would be close... but again the problem is combining all border selectors into one line so that is outputs as valid CSS.

@mixin borders {
  border:($top,$left,$right,$bottom, $type, $color);
}

Using a @mixin is all wrong, I am pretty sure of this... So any help to point me in the right direction would be much appreciated. Thanks in advance..

like image 509
Kris Hollenbeck Avatar asked Dec 11 '22 23:12

Kris Hollenbeck


2 Answers

I was looking to do something similar and ended up with this @mixin.

@mixin border ($style,  $sides...){

    @if ($style != "") {

        @if ($sides == "") {

            border: $style;

        } @else {

            @each $side in $sides {

               @if ($side == 'top' or
                    $side == 'right' or
                    $side == 'bottom' or
                    $side == 'left') {

                    border-#{$side}: $style;

                }

            }

        }

    }

}
like image 195
indieisaconcept Avatar answered Dec 20 '22 15:12

indieisaconcept


Another possibility:

@mixin border( $coordinates: 0 0 0 0, $colour: #000000, $style: solid ) {
  $top: nth($coordinates, 1);
  $right: nth($coordinates, 2);
  $bottom: nth($coordinates, 3);
  $left: nth($coordinates, 4);

  @if not(unitless($top)) {
    border-top: $top $style $colour;
  }
  @if not(unitless($right)) {
    border-right: $right $style $colour;
  }
  @if not(unitless($bottom)) {
    border-bottom: $bottom $style $colour;
  }
  @if not(unitless($left)) {
    border-left: $left $style $colour;
  }

}

$side: 1px;
@include border($side 0 $side 0, black);

CSS Output:

 border-top: 1px solid black;
 border-bottom: 1px solid black;

This way you can avoid having to overwrite styles, but I'd still rather use normal css shorthand if you need to target all the border sides.

Could probably extend this to output the shorthand property if a single $coordinates value is passed. That way at least you can standardise all your border style calls.

like image 32
catdoce Avatar answered Dec 20 '22 16:12

catdoce