Let the height of <p> determine height of <div>
I have a paragraph of text inside a <div>
that varies with length and thus height. I want the div to have a minimum height of 100px
, but grows as the height of <开发者_高级运维p>
increases above 80px
. I set the css property height: 100px
for the <div>
but when the <p>
grew beyond 80px
the text just spills out of the <div>
and the height of the <div>
remains unchanged. What should I do?
Code:
<div id="outer_box">
<div id="box">
<p class="content"> Some long paragraph of content here </p>
</div>
</div>
CSS:
#outer_box {
width: 300px;
min-height: 100px;
}
#box{
width: 300px;
min-height: 90px;
}
The div with id="box"
did change its height to contain the <p>
entirely, but the div with id="outer_box"
did not change its height!
Interested in a CSS solution rather than a jQuery one if possible, I will use whatever works. Reason for choosing a pure CSS solution is because the div
does not exist until the user does a mouseover. Wonder how to target a div
with css that have yet to exist
As Jleagle said, you have to use min-height
. For the most browsers:
height: auto !important;
height: 100px;
min-height: 100px;
Keep the min-height set on the div in your css, I would then use jquery's height function to figure out the paragraph height. Try this in your javascript:
$(document).ready(function(){
var h = $('div p').height();
$('div').css("height", h);
});
Append this to the styles of your div and everything should work fine, also for older browsers:
min-height:100px;
height:auto !important;
height:100px;
Height of div when set to auto lets the content inside it decide its length. However min-height does an override and lets you have a min height for the div
You set the min-height
of the div
, and then you deal with older version of IE via a standard CSS hack:
/* Because of the `* html` part, it only applies in IE, other browsers ignore it */
* html #theDiv {
height: 100px;
}
/* Most browsers use this instead */
#theDiv {
min-height: 100px;
}
Live example
You seem to be missing the word-wrap property. I have tested the following styles in ie9 and chrome. It seems to be working fine.
<!DOCTYPE html>
<html>
<head>
<style>
#outer_box {
width: 300px;
min-height: 100px;
background-color:blue;
}
#box{
width: 300px;
background-color:green;
word-wrap:break-word;
}
</style>
</head>
<body>
<div id="outer_box">
<div id="box">
<p class="content"> Some long paragraph of content here kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk</p>
</div>
</div>
</body>
</html>
精彩评论