Reputation: 87
I have a div with a fixed height, which contains a span with some text and a img element. How can I set the img height to be equal to the div height minus the span height ?
Sample code:
<html>
<head>
<style type="text/css">
div { height: 100px; width: 800px; border-style:solid;}
img { display: block}
</style>
</head>
<body>
<div>
<span>hello world</span>
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
</div>
</body>
</html>
Edit: note: The height/width are fixed values, but are unknown variables.
Upvotes: 1
Views: 93
Reputation: 8409
I have did this with css calc
property take a look on this snippet
img {
display: block;
max-height: calc(100% - 20px);
}
div {
height: 100px;
width: 800px;
border-style: solid;
float: left;
}
img {
display: block;
max-height: calc(100% - 20px);
}
<div>
<span>hello world</span>
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
</div>
Upvotes: 0
Reputation: 260
try to use CSS3 box-sizing property like this.
div {
height: 100px;
width: 800px;
border-style:solid;
box-sizing: border-box;
}
on you html:
<div>
<span>Lorem Ipsum is including versions of Lorem Ipsum</span>
<div>
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" />
</div>
</div>
Upvotes: 0
Reputation: 42352
If flexbox
is an option, you can add this to the div
:
display: flex; // set a flexbox container
flex-direction: column; // column placement
align-items: flex-start; // prevent default stretching in cross-axis (horizontal)
and add max-height: 100%
and min-height: 0
to the image (add min-height: 0
to the span
too) - see demo below:
div {
display: flex;
flex-direction: column;
align-items: flex-start;
height: 100px;
width: 800px;
border-style: solid;
}
img {
display: block;
min-height: 0;
max-height: 100%;
}
span {
min-height: 0;
}
<div>
<span>hello world</span>
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" />
</div>
Upvotes: 1
Reputation: 483
add this in your css, put 100% in your img to fit the height of your div.
img{
display: block;
height: 100%;
}
this is for your text but if you want to fit the image in your div you can use absolute in your text.
span{
position: absolute;
}
Upvotes: 0
Reputation: 1102
Okay, i've personally tried it. Why the height goes down a little it's because of the
<p>Hello World</p>
so it will create a space
The code :
<html>
<head>
<style type="text/css">
div { height: 100px; width: 800px; border-style:solid;}
img { display: block;width:100%;height:100%;}
</style>
</head>
<body>
<div>
<span>hello world</span>
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
</div>
</body>
</html>
Upvotes: 0