Is it possible to implement something like this in CSS?
In css

.margin_($n) {margin: ($n)px;} 

and in html like this:

 <div class='margin_20'>отступили 20 px</div> 

PS Just do not kick much, just my conscience forbade me to write in html style.
PSS Well, kick me off http://jsfiddle.net/hy2dg0uu/

  • almost as possible using preprocessors, but the list of n values ​​should be fixed - Grundy
  • @Grundy can be an example? - wwwplaton Nov.
  • 2
    for example, in scss there are loops and styles you can just generate - Grundy
  • @Grundy well, I can generate it with PHP. Unfortunately not what I wanted. Or am I misunderstanding something? - wwwplaton
  • one
    @wwwplaton, I can’t think of cases where it would be necessary to dynamically hang a margin, and at the same time that it could not be solved with the help of pre-cooked styles. The only thing I can imagine is creating recursive nestings (for example, a tree of files or a tree-like commenting system), but this can also be solved by one single pre-prepared class. Review the structure of the application, because in most cases you can do without the invention of the bike. - neluzhin

3 answers 3

First, specifically in this case there are not the slightest advantages of using the class instead of the inline-style (saving 2 characters is not considered):

 <div class='margin_20'>отступили 20 px</div> <div style='margin:20px'>отступили 20 px</div> 

There is an option that you need a bunch of values ​​with prefixes, then the class really could give something. But it is better to limit yourself to a few predetermined values, and not to push anything. For example, make margin-xs , margin-s , ..., margin-xxl .

As for the question itself, theoretically css allows the imposition of part of the styles to other attributes , but at the moment no browser supports this:

 p[data-ml] { margin-left: attr(data-ml px); } 
 <p data-ml="30">123</p> <p data-ml="50">123</p> <p data-ml="70">123</p> 

  • there is actually no economy, since the style file itself is added - Grundy
  • @Grundy, well, it depends on how many times to repeat. Suddenly, is it there 10,000 times?))) - Qwertiy
  • Wow :-) I didn’t think about this case :) - Grundy

It is completely incomprehensible why this is needed ... However, you can change the style sheet already connected to the document, but not with the help of css. From javascript, you can get style sheets with var styleSheetList = document.styleSheets; Most likely you are doing something wrong, unless the question is for the sake of pure interest.

    With one css this can not be done, unfortunately: (

    • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky