6

I have a div like this:

<div class="center small-top-margin">
  <%= rails code %>
</div>

where `small-top-margin' is as follows:

.small-top-margin {
    margin-top: 2em;
}

Is there a way to pass an argument to a css class such that

class="top-margin(2) #=> margin-top: 2em;
class="top-margin(5) #=> margin-top: 5em; etc..

or even better

class="margin(top, 2) #=> margin-top: 2em;

I've included Rails tags in case there's a way to do this through rails, although a purely css/sass solution would be better.

dax
  • 10,779
  • 8
  • 51
  • 86
  • Not possible to send as parameter to css class – Sridhar R Nov 07 '13 at 08:47
  • 2
    No. I highly doubt it. SASS works by compiling CSS, but `class="identifier"` is not CSS. It is HTML, and it is likley contained in an `ERB` file. You pass arguments to CSS via naming structures, like `top-margin-2`, and you can create dynamically named classes from within SASS: http://stackoverflow.com/questions/16496353/create-dynamic-class-names-using-while-loop – Damien Roche Nov 07 '13 at 08:50

3 Answers3

6

No. But you can generate a reasonable number of pre-built classes:

.top-margin-2 {
    margin-top: 2em;
}
.top-margin-5 {
    margin-top: 5em;
}

Then you can generate your HTML with class="top-margin-#{margin}"

This is not usually a good thing, but if you really need it, it's possible. I urge you though to reconsider and ask what you really want; CSS classes should be semantically meaningful, otherwise you might as well directly apply the CSS on the elements' style attribute. What does 2em mean to you? What is 5em?

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • you're right about 'might as well directly apply' to the style attr. Was more interested if there was a way I could minimize CSS classes, but again you're right - reasonable number seems like the best way to go. – dax Nov 07 '13 at 09:27
0

No it is not possible.

Use LESS or SASS to achieve this.

codingrose
  • 15,563
  • 11
  • 39
  • 58
-1

You can pass parameters to CSS file by using php. 1. Create your style by name style.php as:

<?php
/*** set the content type header ***/
header("Content-type: text/css");
/** set the  color ***/
$page = $_GET['page'];
$font_size = $_GET['font_size'];
if($page==1){
  $color = 'red';
}else{
  $color = 'yellow';
}
?>
#test{
  color:<?=$color;?>;
  font-size:<?=$font_size;?>;
}
  1. In html file call style.php and pass parameter to it

    \link rel="stylesheet" media="screen" type="text/css" href="/css/style.php?page=1&font_size=35px"/>

    div id="test">Test test /div>

Đọc truyện hay
  • 1,913
  • 21
  • 17