简体   繁体   中英

Fit an image inside a div that also has a title?

Here's my fiddle

Here's my HTML:

<div class="block">
    <h2>Title</h2>
    <img src="http://icons.iconarchive.com/icons/martz90/circle/512/camera-icon.png" />
</div>

I'm trying to have an image inside my block. I want to size the image so that it fits inside the block fully. I've tried with height 100% but the title of the block is not taken in to consideration and the height overflows the block.

Try display:table

.block{
    display: table;
}

 .block{ width: 30%; height: 100px; display: table; background: pink; } img{ height: 100%; max-width: 100%; } 
 <div class="block"> <h2>Title</h2> <img src="http://icons.iconarchive.com/icons/martz90/circle/512/camera-icon.png" /> </div> 

One possibility that gives just one constant-pixel value (repeated once):

.block h2 {
  height: 30px;
}

.block img {
  height: calc(100% - 30px);
}
margin-top:-18px

您也可以尝试仅移动图像检查小提琴

What are you trying to do?

If you want do image background - use background-image and fit it

Anyway you can do something like this:

.block{
    width: 30%;
    height: 100px;
    display: block;
    background: pink;
    position: relative;
}

img{
   height: 100%;
   max-width: 100%;
}

h2{
    position: absolute;
    top: 10px;
    left: 100px;
}

https://jsfiddle.net/fe11zyh9/1/

Is it a possibility to set the height of the IMG in px?

So:

img{
   height: 100px;
   max-width: 100%;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM