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.

2
  • Not possible to send as parameter to css class Commented Nov 7, 2013 at 8: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: stackoverflow.com/questions/16496353/… Commented Nov 7, 2013 at 8:50

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

No it is not possible.

Use LESS or SASS to achieve this.

Comments

-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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.