Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coordinating CSS, is there a more straightforward approach than using JS?

I find myself having to use JS too often for what I would consider to be something that ought to be solvable in CSS alone.

Here is an example situation of what I am trying to do:

div.outer { height:{Y}px }
div.inner { padding-top:{Y}px }

I don't really want to specifically set the height of the outer div, but I want is for the padding-top property of the inner div to match the height of the outer div. Is there something about CSS I am missing? Or is JS the usual approach?

In jQuery I'd do something like this:

var y = $('div.outer').height();
$('div.inner').css('padding-top',y+'px');

Although rare, what about clients that disable JS?

Clarification: Please notice that this is not so much a "how do I do this in CSS" question. I am aware that currently, you cannot do this in CSS. Rather it is more of a question about what other sorts of solutions might accomplish the coordination that I am after. I can write CSS in PHP with vars if I wanted to just calculate values for initial delivery, but that's not what I'm after. It is more about coordinating two elements so that when one changes (due to the window being resized or a device being rotated, or another element being introduced via AJAX, etc.) another element's styling also changes to match it.

like image 589
Octopus Avatar asked May 30 '14 18:05

Octopus


1 Answers

The answer is no it's not possible (at this moment). By pure coincidence I stumbled upon the fact that apparently, you can only set the padding-top property relative to the parent element's width!? In your demo case that'd be:

div.outer { width: 400px; }
div.inner { padding-top: 50%; } /* will be exactly 200px */
/* You can also set a relative width (%), or inherit it */

I've made a little test case that demonstrates this: http://jsbin.com/rukabaso/1/edit. Resize the output window to see the values. When set to 50%; the padding-top property is exactly 50% of the parent's width, because apparently:

Percentages on all padding/ margin properties refer to the parent's width

For reference: How is padding-top as a percentage related to the parent's width?

like image 89
webketje Avatar answered Oct 17 '22 11:10

webketje