user1452062
user1452062

Reputation: 805

Responsive image inside a div with padding

We have an #inner with padding-top and padding-bottom. The content inside the div is centered. We have an image to with max-width:100% and max-height:100%.

The image is responsive but it gets the height of the #inner with padding, and it's not centered.

CSS

*, *:before, *:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

#inner {
    height:100px;
    padding:15px 0;
    background:yellow;
}

#container {
    height: inherit;
}

a {
    float: left;
    height: inherit;
    width: auto;
}

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

The HTML:

<div id="inner">
    <div id="container">
        <a href=""><img src="http://lorempixel.com/400/200/"></a>
    </div>
</div>

I tried to add padding to the <a> tag, add an other container around the <a> but the image became smaller. The image should be the height of the #inner - 30px (padding).

I understand the problem is with the inherit property, but I don't know the solution.

Here is the jsfiddle link: http://jsfiddle.net/b8o2t31e/

Upvotes: 1

Views: 6296

Answers (2)

G.L.P
G.L.P

Reputation: 7217

Try like this: Demo

CSS:

#container {
    height: 100%;
}
a {
    float:left;
    height: inherit;
    width: auto;
    background:red;
}
img {
    max-height:100%;
    max-width:100%;
    display:block;
    margin:0 auto;
}

Edit : or if you want to place image in center of div you can use like this Demo

CSS:

#container {
    height: 100%;
    background:red;
    display:block;
    margin:0 auto;
    text-align:center;
}
a {
    max-height:100%;
    width: auto;
}
img {
    max-height:100%;
    max-width:100%;
}

Edit : To remove Extra space use width and height as 100% for <img> like this: Demo

CSS:

#container {
    height: 100%;  }
a {
    height: inherit;
    background:red;
    margin:0;
    padding:0;
    display:inline-block;
}
img {
    height:100%;
    width:100%;
}

Upvotes: 2

Timur Osadchiy
Timur Osadchiy

Reputation: 6249

Try changing height of the #container from inherit to 100%.

*, *:before, *:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

#inner {
    height:100px;
    padding:15px 0;
    background:yellow;
}

#container {
    height: 100%;
}

a {
    float: left;
    height: inherit;
    width: auto;
}

img {
    max-height:100%;
    max-width:100%;
}
<div id="inner">
    <div id="container">
        <a href=""><img src="http://lorempixel.com/400/200/"></a>
    </div>
</div>

Upvotes: 1

Related Questions