Friday 27 April 2012

CSS positioning and Stacking images in rails.

So you are using Ruby on Rails and you want a method of stacking images on top of each other.
Your answer will probably involve CSS but many of the blog posts and Q&A posts I found weren't too descriptive so here is my shot at explaining this from the perspective of someone who doesn't use CSS often.

First a short bit on parents in CSS

When using CSS, having one style inside the other makes the top level the parent. In this example the div with the id of "container" is the parent of the div with the id of "contained".

<div id="container">
<div id="contained">
</div>
</div>
This does not work with class instead of id.

<div class="container">
<div class="contained">
</div>
</div>

And the CSS position

There are several good resources explaining position and I will just link to my favourites.
http://www.barelyfitz.com/screencast/html-training/css/positioning/

Onto the good stuff

Our CSS files are in assets/stylesheets/ and the one we are using is the application wide stylesheet application.css.scss

The technique is to have a position:relative parent container, so that all position:absolute items inside are in the same place against the relative container. Note that the container needs a size, it will not take the size of absolute children. My images are 64px*64px big so I have to force my container to be that large or the next HTML element in the flow will overlap it.
In application.css.scss

#container {
    position:relative;
    width: 64px;
    height: 64px;
}
#image {
    position: absolute;
    top: 0;
    left: 0;
}
This lets you place images with the id="image" inside a div of id="container". In my code I stack City.png vertically above Grass.png in the view. Note in versions of Rails before 3.1 you need to use :id => instead of the new syntax id:
<div id="container">
<%= image_tag("Grass.png", id:"image") %>
<%= image_tag("City.png", id:"image") %>
</div>

No comments:

Post a Comment