Can CSS values ​​change relatively?

#foo{font-size:14px;} 

#Foo now has a font size of 14px

 #foo{font-size:$-2px} // Hypothetical code 

Now #foo has a 12px font size. (14px - 2px)

Is this possible in any way? To dynamically change the value of a selector.

+7
html css
source share
3 answers

1. Using the calc () method

I do not understand what you mean by dynamic change. But to do a relative calculation, use the calc() method.

Example:

 width: calc(100% - 80px); 

2. Using a preprocessor such as SASS

You can also check out Sass for preprocessing. One of the well-supported functions is variables.

You can define variables and do some calculations.

 $body-size: 200px; body { width: $body-size/2 ; } 

Here is a simple example that I created: jsfiddle

Link: SASS

3. Using jQuery

OP mentions resizing when resizing a window. One approach would be to use jQuery

 $(window).resize(function() { var width = $(window).width(); var height = $(window).height(); $('#item').width(width); }); 

4. Using the vw and vh attributes

The OP mentioned the desire to resize according to the viewport in the comment.

vw and vh refers to the width and height of the viewport, respectively.

 div.responsive { width: 10vw; /* 10% of viewport width */ height: 10vh; /* 10% of viewport height */ background-color: black; /* Just to make it visible while testing */ } 
+3
source share

You can use rem , which will refer to the global font size.

 :root { font-size : 14px; } #foo { font-size : calc(1rem - 2px); } 
 <div> I am a 14px text according to the root font-size </div> <div id="foo"> I am a 12 pixel text according to the rem font-size </div> 

EXPLANATION

Rema will reference global css. Therefore, when processing (1rem - 2px) it is actually (14px - 2px).

+3
source share

My $ 2/100.

  • CSS currently doesn't allow cross browser variables to be used in the true sense, but you might be interested in this CSS Variables. White paper
  • CSS that does not support variables is one of the most important reasons for CSS preprocessors. eg. SASS , LESS .
  • You can use font-size and then relative em to control some properties of the elements, but are somewhat annoying, and you will have to individually determine the font size for the child elements.

     .example { font-size: 20px; border-radius: .5em; // 10px (20*.5) padding: 2em; // 40px (20*2) } 
+1
source share

All Articles