Set width (or height) of element as percentage of higher ancestor element
If I have a DOM structure with three DIVs A, B & C where C is a child of B; and B is开发者_JS百科 a child of A - is there a way to set the width (or height) of C to be a percentage of the width (or height) of A?
PS: jQuery is available, and any jQuery functionality can be used.
Well, in that case, try $('#c').height( $('#c').parent().parent().height() * pct/100 )
If it has to be calculated once only (no resize problems), just fetch the height of A and set the height of C accordingly.
var heightA = $('#divA').height();
var heightC = heightA * 0.50; // 50%
$('#divC').height(heightC);
Try this
$(function(){
var height = $("#A").height();
var width = $("#A").width();
$("#c")
.width(width * 0.10);//10%, you can set whatever percent you need
.height(height * 0.10);//10%, you can set whatever percent you need
});
This would work:
var height_A = $('#div_A').height();
var width_A = $('#div_a').width();
$('#div_C').height(height_A*0.30); // for 30%
$('#div_C')width(width_A*0.30); // for 30%
Assuming A's parent has no width defined and A and B can't be width:100% for a much more lightweight and sensible CSS solution:
$('#divC').height( $('#divA').height() * (percentage/100) );
If this is for a real-world problem, it's a bad solution. Never solve layout problems with the JS-hammer.
The following would be ideal.
#parent_of_a { width:<anything>; }
#a, #b { width:100%; }
#c { width:<whatever>% };
CSS % width requires that an element's parent's width is defined.
Try this:
$(function(){
var aheight = $("#a").height();
var awidth = $("#a").width();
$("#c").width(awidth * 0.50).height(aheight * 0.50);
});
You shouldn't solve layout issues with JavaScipt, since JS can be disabled. That being said...
This code should work even if the window is resized.
function setDimension() {
var containerWidth = $('#divC').parent().parent().width();
$('#divC').width(containerWidth * 0.5);
}
$(setDimension); // do it on initial load
$(window).resize(setDimension); // do it when window is resized
HTML width
supports percentages. I don't see how you'd need to do anything special to make it work.
精彩评论