0

Is it possible to set the font size relative to another element's font size using only SCSS and not JS?

For example, I want to get paragraph text 2 pixels smaller then input.

I've attempted something like this but it does not seem to work:

HTML

<input type="text" value="This is input text">
<p>Text smaller then input</p>

SCSS

$isize: 16px;
$psize: $isizev - 2;

input {
  font-size: $isize;
}

p {
  font-size: $psize;
}
brooksrelyt
  • 3,925
  • 5
  • 31
  • 54
santa
  • 12,234
  • 49
  • 155
  • 255
  • 1
    `$psize: $isizev - 2px;`? – Flying Jan 15 '19 at 21:45
  • Thanks. I've tried it on JSfiddle.net but it doen't seem to work. Or perhaps JSfiddle's SCSS rendering is broken... Is there another place it can be tested online? – santa Jan 15 '19 at 22:06
  • 1
    yes, [sassmeister](https://www.sassmeister.com/gist/f4feed17dbc10208e9a2d26928a2b97e). You've also had a typo, `$isisev` instead of `$isize` – Flying Jan 16 '19 at 10:13

2 Answers2

1

We can also rely on the browser calc() function as per: https://caniuse.com/#search=calc()

$isize: 16px;
$psize: calc(#{$isize} - 2px);

input {
  font-size: $isize;
}

p {
  font-size: $psize;
}
Webnatural
  • 26
  • 2
  • Uh, I like this idea even more! What's the '#' for? – santa Jan 16 '19 at 16:07
  • 1
    It allows using variable value inside the property value inside the calc() function. It is so-called interpolation as shown in example [here](http://sass-lang.com/documentation/file.SASS_REFERENCE.html#interpolation_). Without it, the variable wouldn't be parsed. – Webnatural Jan 16 '19 at 22:58
0

Maybe using a function?

SCSS

@function ratioDimensions($factor:1, $base-dimension:16, $unit:px) {
  $calcSize: $base-dimension * $factor;
  @return #{$calcSize}#{$unit};
}

And then you can use:

SCSS

$isize: ratioDimensions(1);
$psize: ratioDimensions(1,16-2,px);

input {
  font-size: $isize;
}

p {
  font-size: $psize;
}
Webnatural
  • 26
  • 2
  • This looks interesting , but unfortunately I already have a font-size set for input in px... – santa Jan 15 '19 at 22:12
  • Hmmm, pls have a look at the [link]https://www.sassmeister.com/gist/884fd97bc9df98f65114994e57901300 I assumed that there is only px unit used. – Webnatural Jan 15 '19 at 22:38