Adjust width based on parent w / jQuery

I need to adjust the width of the class based on the width of the parent. Currently .myClass has the width assigned in CSS. There will be something like this work:

.myClass { color: #000; width:100px; } $(".myClass").width($(".myClass").parent().width()); 

This will apply to <DIV> , and the parent can be <TD> or another <DIV> .

+6
source share
2 answers

That you should work, but I would probably change it to this:

 $(".myClass").css("width",$(".myClass").parent().css("width")); 

You may be able to use this instead of the second $(".myClass") , but you will have to check this.

Keep in mind that he does not change the class itself. It changes the width of any element that uses this class.

UPDATE:

If you intend to do any calculations with the width of the parent, you should probably stick to your original method. I like css when you apply styles as is, but this is a personal preference. If you make any modifications to the parent value, then width is probably better.

From the width documentation:

It is recommended to use the .width () method when the width of an element should be used in mathematical calculation.

+5
source
 var parentW = $('.myClass').parent().width(); $('.myClass').width(parentW); 

Demo1

 $('.myClass').width( $('.myClass').parent().width() ); 

Demo2

And if you have more "myClass" classes:

 $('.myClass').each(function() { var myClass = $(this); var parentW = myClass.parent().width(); myClass.width(parentW); }); 

Demo3

AND HERE ONE HARD CODE: (no javascript);)

Demo4

And if you followed this song, here is the β€œrefrain”: (intellectual decision) :

 $('.myClass').css({width: 'auto'}); 

Demo5

+2
source

Source: https://habr.com/ru/post/891840/


All Articles