0
div {
    display:block;
    width:320px;
    background:url('images/cnon.jpg');
    background:contain;
}

Is there any way to auto-adjust <div> height depending on background height?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Jay
  • 143
  • 3
  • 14
  • 2
    Possible duplicate of [How to get div height to auto-adjust to background size?](http://stackoverflow.com/questions/600743/how-to-get-div-height-to-auto-adjust-to-background-size) – John Slegers Mar 07 '16 at 17:47

3 Answers3

0

I can't understand what do you actually want, but if you want to make div fully aligned to background:

div {
    display:block;
    width: auto;
    height: auto;
    background:url('images/cnon.jpg');
    background:contain;
    margin: -10px; //Optional
}

Sorry if i didn't understood your question well.

Stefan Đorđević
  • 565
  • 1
  • 4
  • 22
0

if you could use jQuery you can handle it simply by checking on the img height then apply this height to the div itself

Peter Wilson
  • 4,150
  • 3
  • 35
  • 62
0

You can adjust the height of div, adjusting the padding top of the div, just need to set the css automatically.

.div_image{
    background:url('images/cnon.jpg');
    height: 0;
    width: 100%;
    background-size: contain;
    padding-top: 20%;
}

The padding-top is calculated by a formule.

(image-height[px] / image-width[px]) * container-width[%]

Example: (274px / 1370px) * 100% = 20%

With this result the padding-top need to be 20%.

techspider
  • 3,370
  • 13
  • 37
  • 61