Can I calculate and use element height with SASS \ Compass

Dmitry Belaventsev picture Dmitry Belaventsev · Mar 30, 2013 · Viewed 53.8k times · Source

I use sass and compass in my RoR project. I need to assign to the top CSS property of an element the value, which is element height divide by -2. Can I do it with SASS \ Compass?

Answer

Andrey Mikhaylov - lolmaus picture Andrey Mikhaylov - lolmaus · Mar 30, 2013

You seem to have got the XY problem. You have a task to solve, and instead of asking us about the task, you ask about a solution that you tried and already found inappropriate.

Why do you want to apply the top property equal to half of element's height and negated? Because you want to move an absolutely positioned element half its height up. This is the original task.

There's a simple solution to achieve that, and SASS is not even necessary! (Actually, as long as you don't know element's height, SASS can't provide more help than CSS.)

We'll need an extra wrapper:

<div class=container>
  <div class=elements-wrapper>
    <div class=element>
    </div>
  </div>
</div>

To push the element up for 50% of its height, do two simple steps:

1) Push its wrapper up fully out of the container:

.elements-wrapper {
  position: absolute;
  bottom: 100%; }

2) Now pull the element down for 50% of its height:

.element {
  margin-bottom: -50%; }

That's it!

When you do margin-bottom: -50%, you actually pull the element 50% down of its wrapper's height. But the wrapper's height it equal to the element's height!

Don't forget to apply position: relative to the container, otherwise position: absolute will relative to the window, not the container.

Here's a demo with well-commented code: http://jsbin.com/uwunal/4/edit

UPD 2013-04-16

I've just realised that this is a phony.

In CSS the percentages of top and bottom margins refer to the width of the container. So the above example only works because the container is square.