CSS: the height of the last child should be based on previous siblings, but not overflow the parent

Corresponding JS Fiddle http://jsfiddle.net/arosen/FMQtR/

Problem

My HTML looks something like this:

<div id='parent'> <div id='one'> A variable amount of text here. </div> <div id='two'> A less important variable amount of text here. </div> </div> 

#parent div is a fixed height and cannot be changed. Inside it, I have at least two child divs. The first (or many) will have an unknown amount of text in it, determining its height. Based on the content of the first, I want the latter to occupy the same height as in the parent, but not overflow.

My current CSS example:

 #parent { border: 1px solid #000; height: 150px; width: 150px; } #one, #two { border: 1px dashed #333; height: auto; margin: 5px; padding: 5px; overflow: hidden; } 

My current JS solution

 function() { var $two = $('#two'); var $parent = $('#two').parent() $parent.css('overflow', 'hidden'); var heightDifference = $parent[0].scrollHeight - $parent.height(); $two.css('height', $two.height() - heightDifference); } 

I am wondering if there is a CSS layout or HTML solution to this problem, or should I use the JS solution that I have in the script that runs when the last button is clicked.

EDIT My JS script has been updated, since the text does not change once on the page, but depending on the information downloaded from the server, it will not know how much text it will have until the page is displayed.

EDIT 2 Only modern (and IE 9) browsers must be supported.

EDIT 3 The final div must be tall as it is used by other jQuery plugins.

+7
source share
2 answers

Not. You can not. CSS is not a programming language. Instead, each tuple selector{ property:value; } selector{ property:value; } defines a rule for a specific set of elements. Actual style, such as current height, current width, or other properties, may not be available in CSS.

Someone might think, β€œwhat about percentages?” Well, they are based on the containing block, which is often the parent element (in this case #parent ).

Thus, you need to specify a fixed height for all div (which is not possible according to the information you provide) or use a JavaScript based solution.

+3
source

You can accomplish this if you are not too tuned at the borders / margin / indentation / line-height. Just make sure (the parent div - (all fields / padding)) is completely divisible by your line height, you will never see partial lines or overflow. However, with your border styles, you cannot achieve this with CSS alone.

You can still hack it by adding another element to the parent div, say a dotted paragraph paragraph tag and a thick white bottom border located to hide the overflow border with the above solution ... but this is a hack that I'm not a fan of, and has the ability to easily break in browsers.

TL; DR - Just use JS.

0
source

All Articles