Home > Software engineering >  Using variable values in a class in HTML/SCSS
Using variable values in a class in HTML/SCSS

Time:10-28

I am pretty new to html/css/sass and I'm currently developing a website for myself. When aligning items I notice that I sometimes want a padding of 1em to the right for one item, and then a padding of 2em to the top for another item etc. I do the definitions in a .scss file like this currently:

_master.scss:

:root {        
    --pad-neg-left-1: 0 0 0 -1em;
    --pad-top-2: 2em 0 0 0;
}

.pad-neg-left-1{
    padding: var(--pad-neg-left-1);
}
.pad-top-2{
    padding: var(--pad-top-2);
}

index.html:

<div > Hi </div>

This gets big and complex really fast if I want to add classes to my html objects to fit all purposes. Instead I would like a class that can take parameters and use it maybe like this:

_master.scss:

function pad(top, right, bottom, left){
    padding: top right bottom left;
}

index.html:

<div > Hi </div>

Is this possible?

I could write my div as this instead: <div style="padding: 2 0 0 0;"> Hi </div> but for some reason I heard from videos that it is bad to define styling straight in html and instead use classes. Is this wrong, or can I use some other approach?

CodePudding user response:

I am not understanding why you have to complicate the process. You can directly write the css by setting class. But if you want to create a style standards you can use @mixin and @include or variable for your situation.

eg:

 @mixin padding($top:0, $right: 0,$bottom:0, $left:0) {
  padding: $top $right $bottom $left;
}

.avatar {
  @include padding(2,0,0,0);
}

CodePudding user response:

To create variables in sass, $variableName: syntax is used and @mixin for reusable code.

_master.scss

@mixin applyPaddings($padding-top, $padding-right, $padding-bottom, $padding-left) {
  padding: $padding-top $padding-right $padding-bottom $padding-left;
  // or you can do it separately like
  // padding-top: $padding-top;
  // ...
}

.paddings {
  @include applyPaddings(1rem, 1rem, 1rem, 4rem);
}

index.html

<div > Hi </div>

CodePudding user response:

You could use a styling solution like tailwind which contains a lot of utility classes for styling things.

This will allow you to customize styles for different elements without directly writing any css.

https://tailwindcss.com/

  • Related