Relevant JS Fiddle http://jsfiddle.net/arosen/FMQtR/
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>
The #parent div is a fixed height and cannot change. Within it, I have at least two child divs. The first one (or many) will have an unknown amount of text in it determining its height. Based on the content of the first one, I want the last one to take up as much height is left in the parent but not overflow.
My current example CSS is:
#parent {
border: 1px solid #000;
height: 150px;
width: 150px;
}
#one, #two {
border: 1px dashed #333;
height: auto;
margin: 5px;
padding: 5px;
overflow: hidden;
}
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'm wondering if there is a CSS layout or HTML solution to this problem or if I must use the JS solution I have in the fiddle that is run on the push of the last button.
EDIT Updated my JS fiddle as the text will not change once on the page but depending on information loaded from the server, will not know how much text it will have until the page is rendered.
EDIT 2 Only modern (and IE 9) browsers need to be supported.
EDIT 3 The final div must have a height as it is used by other jQuery plugins.
The :last-child selector is a pseudo-class that allows you to target an element that is the last child element within its parent. See also :first-child, :nth-child, :nth-last_child, and :only-child selectors.
If the parent div does not need to be position:relative, simply set the children styles to visibility:visible. If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed.
No. You can't. CSS isn't a programming language. Instead every selector{ property:value; }
tuple defines a rule for a specific set of elements. The actual style such as current height, current width or other properties cannot be accessed in CSS.
Someone might think "what about percentage values"? Well, those are based on the containing block, which is often the parent element (in this case #parent
).
So you either have to specify a fixed height for all div
(which isn't possible according to the information you gave us), or use a JavaScript based solution.
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