Search code examples
javascriptjquerycsshtml

Referencing another element in CSS / doing math in CSS


I have two divs nested inside of a div.

<div id='outer' class='one'>
    <div id='inner'></div>
    <div id='button' class='bttn'>Click me!</div>
</div>

The outer div's height is a percentage of the page. I'd like one of the inside div's height to be a fixed difference away the outer div (i.e. $('#inner').height($('#outer').height() - 35)), because the second inner div is essentially a button with fixed height (35). I'd like this to happen even when I change the height (through CSS triggers (:hover/adding a class/etc. so I can use Transitions) or otherwise).

I googled around a bit and saw Less might be an answer, but from what I can tell it compiles in to static values, but I still need to use percentages, since I want this app to work/feel the same on any screen size.

I have examples of what I'm currently doing/how I'm thinking about it in some jsfiddles.

Current 'solution': http://jsfiddle.net/L9NVj/5/ (End heights are what I want them to be, but the transition looks terrible)

Idealistic 'solution': http://jsfiddle.net/L9NVj/6/ (End heights are wrong, but the inner div hugs appropriately)

Potential solution: http://jsfiddle.net/L9NVj/7/ (This hides the inner div on click and then shows it again when the appropriate size has been reached)

Any help/thoughts/insights would be greatly appreciated!


Solution

  • Consider absolute-positioning the inner elements, since the outer's size isn't controlled by their size/position.

    #inner {
        position: absolute;
        top: 2px;
        left: 2px;
        right: 2px;
        bottom: 35px;
        /* ... */
    }
    
    .bttn {
        position: absolute;
        bottom: 2px;
        left: 2px;
        /* ... */
    }
    

    Example: http://jsfiddle.net/L9NVj/9/