Fernando Souza
Fernando Souza

Reputation: 1779

Adding 1px to font size of every element inside a certain element

Is there a way to add 1px to the current font-size of every element inside .wrap, without doing it manualy?

 .wrap{
      margin-top: 169px;
      .element1{
       font-size:30px;
      }
      .element2{
       font-size:20px;
      }
    }

Upvotes: 1

Views: 618

Answers (2)

jaredgorski
jaredgorski

Reputation: 540

There's no way to do this with normal CSS unless you use relative values (like em) and then set the font-size on body. What this does is create a standard font-size (whatever size you set on body) and then multiply it by whatever you set as the em value in your nested CSS. For example, if you set body to font-size: 16px; and then set everything else to 1em (same as 16px) or 2em (32px), etc., you can control this base size simply by changing the font-size on body.

body {
  font-size: 16px;
}

h1 {
  font-size: 2em;  // 16 * 2 = 32px
}

p {
  font-size: 1.5em;  // 16 * 1.5 = 24px;
}

Also, since it appears you're using SASS, you can create variables for font-size and then change those variables.

$font-size-sm: 16px;
$font-size-lg: 32px;

h1 {
  font-size: $font-size-lg;
}

p {
  font-size: $font-size-sm;
}

You can also do math with these variables (as noted by Matt Fryer), so you could technically add the font-size to a variable if you don't care about keeping the same scale ratios between different font-sizes. (What I mean is that 16px / 32px is a different ratio from (16px + 1px) / (32px + 1px). If you scaled these changes up higher, you'd notice that the relative sizes were wonky.)

I work on a project where, depending on the environment, we add 1px to all font-sizes. The way we do this is we define all of the font-sizes in our design language in SASS variables on the sheet we use to import all of our .scss files for the build module. We have two of these sheets: one for each environment. The sheet for the environment with "font-sizes +1" simply has all of the font-size variables set to the "+1" values.

Upvotes: 1

user1247034
user1247034

Reputation:

Just use a SASS variable, like this:

$var: 1px;

.wrap
{
    margin-top: 169px;
    .element1
    {
        font-size: 30px + $var;
    }
    .element2
    {
        font-size: 20px + $var;
    }
}

Upvotes: 1

Related Questions