How to set dynamic width on floating div?

I have a div container with 3 div elements inside (A, B and C). I find out the width of the container and the width of A and B) the problem is that in some cases B will not be there, in this case I need C to expand to fill the rest of the container. How do I do this using direct css or will I need to use javascript to calculate the width?

Thanks.

+4
source share
5 answers

In your example, the contaner div is 400 pixels wide. The total width of div a and div b is 495 pixels!

The wider the width of the container and why div c covers only 400 pixels.

But if you change the width of the container to something like 900px, you will see that div c occupies the rest of the space. Here is a look: http://jsfiddle.net/SWQ6h/3/ .

+1
source

With CSS 3 selectors, you can do something like this:

 CONTAINER { width: 1000px } CONTAINER A { width: 250px } CONTAINER B { width: 250px } CONTAINER C { width: 500px } CONTAINER A + C { width: 750px } /* if C is next to A in the source, and assuming B is therefore not present, increase C width to 750px. */ 

Of course, this method requires that the element C immediately follow A in the source. Also worth mentioning is the selector + (as well as the load on the bucket of other awesome CSS3 stuff) is not supported in IE6, but is supported in IE7, IE8 and all other class A browsers.

I can only pray that you see the light and already lose IE6.

0
source

I am going to propose another separate answer using the CSS 3 selector. My other answer, although simple and elegant, may not apply to your specific situation.

A more bulletproof way to achieve what you are looking for is this:

 CONTAINER { width: 1000px } CONTAINER A { width: 250px } CONTAINER B { width: 250px } CONTAINER C { width: 750px } CONTAINER B ~ C { width: 500px } /* if the B element is present, and is a sibling of C, reduce C width to 500px */ 

The only caveat in this method is that elements B and C should be siblings, and according to the sounds of things - in your case.

0
source

If you do not specify a width at all or a height, if the div would not be displayed, if something was not in it. You can use the minimum and maximum width attributes to handle this.

In this case, I would have: divs for A, B and C that have no properties and all are float. Around these divs, I will have a div container with a certain width and height, and the overflow will be hidden. I would assign A, B and C max widths that are suitable (I'm not sure that someday there will be a situation when they say that B and C are not there, and A needs to be filled).

0
source

You can use jQuery to calculate the width of the word "C" along the lines

 var Container = $('#container').width(); var A = $('#A').width(); var B = $('#B').width(); var C = Container - (A+B); $('#C').css('width', C +'px'); 

I did not test it, but you understand.

0
source

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


All Articles