I need to be able to adjust a width of a class based on a width of a parent. Currently .myClass has a width assigned in CSS. Would something like this work:
.myClass {
color: #000;
width:100px;
}
$(".myClass").width($(".myClass").parent().width());
This will be applied to a <DIV>
and the parent could be a <TD>
or another <DIV>
.
jQuery width() Method The width() method sets or returns the width of the selected elements. When this method is used to return width, it returns the width of the FIRST matched element. When this method is used to set width, it sets the width of ALL matched elements.
Set the padding to 0 in the parent. So in the parent css class add padding: 0px; this should fix it. You may also need to set margin: 0px; in the child css class. Also try display: block; .
Method 2: We can make the display attribute of the child container to table-row and display attribute of parent container to table, that will take all the height available from the parent div element. To cover all the width, we can make the width of parent div to 100%.
The parent() is an inbuilt method in jQuery which is used to find the parent element related to the selected element. This parent() method in jQuery traverse a single level up the selected element and return that element. Syntax: $(selector).parent()
What you have should work but I would probably change it to this:
$(".myClass").css("width",$(".myClass").parent().css("width"));
You might be able to use this
instead of the second $(".myClass")
, but you'd have to test that.
Keep in mind that it's not changing the class itself. It's changing the width of any element that uses that class.
UPDATE:
If you are going to be doing any sort of calculations with the parent width then you should probably stick with your original method. I like css
when you are applying styles "as is" but that is a personal preference. If you are doing any kind of modifications to the parent value then width
is probably better.
From the width documentation:
The .width() method is recommended when an element's width needs to be used in a mathematical calculation.
var parentW = $('.myClass').parent().width();
$('.myClass').width(parentW);
$('.myClass').width( $('.myClass').parent().width() );
And if you have more classes 'myClass':
$('.myClass').each(function() {
var myClass = $(this);
var parentW = myClass.parent().width();
myClass.width(parentW);
});
AND HERE IS ONE HARD CODED: (no javascript);)
And if you followed this song, here is the 'refrain': (the smart solution):
$('.myClass').css({width: 'auto'});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With