Created
May 22, 2016 16:43
-
-
Save beaugaines/db880be2d67c0a12f7c69b45d310873a to your computer and use it in GitHub Desktop.
random colors in sass
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @mixin random-color($selector) { | |
| #{$selector}: unquote("rgba(#{random(256) - 1}, #{random(256)-1}, #{random(256 - 1)}, #{random(100)/100})"); | |
| } | |
| $tags: (h1, h2, h3, h4, h5, p, li, a, strong, small, em); | |
| @each $tag in $tags { | |
| #{$tag} { | |
| @include random-color('color'); | |
| } | |
| } | |
| body { | |
| @include random-color('background-color'); | |
| } |
I tried this code, but it does not work. Where's the mistake?
In app/assets/stylesheets/topics.scss, to set the background-color attribute for ten available classes (bg-color-1, bg-color-2, etc...):
@mixin random-color($selector) {
#{$selector}: unquote("rgba(#{random(256) - 1}, #{random(256) - 1}, #{random(256) - 1}, #{random(100)/100})");
}
@for $i from 1 to 10 {
.bg-color-#{i} {
@include random-color('background-color');
}
}
In app/helpers/topics_helper.rb, I create a helper to set randomly a class from the classes array to be used in topics#show:
def random_class
classes = [
"bg-color-1",
"bg-color-2",
"bg-color-3",
"bg-color-4",
"bg-color-5",
"bg-color-6",
"bg-color-7",
"bg-color-8",
"bg-color-9",
"bg-color-10"
]
classes.sample
end
In app/views/topics/show.html.erb, where I call the helper method to set the class that should give the random background color to the paragraph:
<% @topic.bookmarks.each do |bookmark| %>
<div class="media">
<div class="media-body">
<p class="<%= random_class %>">
<%= link_to bookmark.url do %>
<%= bookmark.description %>
<% end %>
</p>
</div>
</div>
<% end %>
I wrote bg-color-#{i} instead of bg-color-#{$i}.
Now it works
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The fact was that I wanted a different
background-colorfor everydiv.media p, and I coulodn't afind a way to achieve that with sass.To do that I should pass the instance variable
@topic.bookmarksor at least the value of@topic.bookmarks.countto the stylesheet, and for what I've found around it's not possible.This code
Gives this result:
While I wanted this:
I really cannot imagine a way to achieve this in sass without the possibility to pass the before-mentioned variable.