CSS值可以相对改变吗?

dom*_*rix 7 html css

#foo{font-size:14px;}
Run Code Online (Sandbox Code Playgroud)

现在#foo的字体大小为14px

#foo{font-size:$-2px} // Hypothetical code
Run Code Online (Sandbox Code Playgroud)

现在#foo的字体大小为12px.(14px - 2px)

这有可能吗?动态更改选择器的值.

gec*_*kob 3

1. 使用 calc() 方法

我不明白你说的动态变化是什么意思。但要做相对计算,要用calc()方法。

例子:

width: calc(100% - 80px);
Run Code Online (Sandbox Code Playgroud)

2. 使用SASS等预处理器

您可能还想检查Sass预处理。受良好支持的功能之一是变量。

您可以定义变量并进行一些计算。

$body-size: 200px;

body {
  width: $body-size/2 ;
}
Run Code Online (Sandbox Code Playgroud)

这是我创建的一个简单示例:jsfiddle

参考:SASS

3.使用jQuery

OP提到每当窗口大小改变时就改变大小。一种方法是使用 jQuery

$(window).resize(function() { 
    var width = $(window).width();
    var height = $(window).height();

    $('#item').width(width);
});
Run Code Online (Sandbox Code Playgroud)

4. 使用vwvh属性

OP 在评论中提到想要根据视口更改大小。

vwvh分别相对于视口宽度和高度。

div.responsive {
   width: 10vw; /* 10% of viewport width */
   height: 10vh; /* 10% of viewport height */
   background-color: black; /* Just to make it visible while testing */
}
Run Code Online (Sandbox Code Playgroud)