问题
Relevant 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>
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;
}
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'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.
回答1:
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.
回答2:
You could accomplish this if you're not too set on borders/margin/padding/line-height. Just make sure that (parent div - (all margins/padding)) is wholly divisible by your line-height, you'd never see partial lines or overflow. However, with your border styles you can't achieve this through CSS alone.
You could still hack it by adding another element to the parent div, say a paragraph tag with the dashed border-top, and a thick white bottom border, positioned to hide the overflowing border with the above solution... but that's hacky, which I'm not a fan of, and has a potential to break easily across browsers.
TL;DR - Just use your JS.
来源:https://stackoverflow.com/questions/10852621/css-last-child-elements-height-should-be-based-on-previos-siblings-but-not-ove