CSS property value from class name

2019-02-03 20:25发布

问题:

It is possible to pass parameters for CSS in class name? For example:

.mrg-t-X {
   margin-top: Xpx;
}
<span class="mrg-t-10">Test</span>

In this example X should be 10.

回答1:

No it isn't. The closest we have to this is the attr() function, but that only works within the content property:

figure::before {
  content: attr(data-before) ', ';
}

figure::after {
  content: attr(data-after) '!';
}
<figure data-before="Hello" data-after="world"></figure>

Perhaps one day this will be expanded so that we can use it elsewhere, but for now this isn't possible.

Currently as I'm sure you're aware if you want to be able to use the .mrg-t-X class, you'll need to define separate style rules for each X you wish to allow:

.mrg-t-1 { ... }
.mrg-t-2 { ... }
.mrg-t-3 { ... }
...


回答2:

no your code is wrong but you can write css inside the tag

*<span style="margin-top:Xpx;">*


回答3:

It isn't possible to directly pass parameters using just CSS but you're not the first person to ask - check out this question which looks at CSS and JavaScript options and also this might be helpful regarding attribute selection.

This will only help if you are looking at a few variables of margin-top but I don't know what context you're using this in. Depending on what you're using it for there might be better ways.

The simplest way would probably be just to add the style inline to your span <span style="margin-top:10px"> but I try to stay away from inline CSS!



回答4:

Maybe you are looking for SCSS or LESS. It have mixins, variables, etc, and it autocompile real and long css. It was maded to this purposes and write less and less css with the same result.

http://sass-lang.com/guide

http://lesscss.org/

 @size: 10px;
 .class { font-size: @size;  }

Good luck!