David
David

Reputation: 4873

Preventing a height change when adding a border with box-sizing

I'm unable to find something that describes this issue, but if I'm missing it, just let me know.

Below is a demo (Tested in IE11 and Chrome) which shows the problem perfectly

Essentially, I'm trying to add a border to an element, and keep the size the same. It's working perfectly for the width, but the height, it only accommodates half of it, so I have an extra 3px in height.

Is there a way to prevent this / get around it without using a script? I can make changes specifically to the element(s) which have the border, but I don't know the actual height (200px is used here just for demo purposes, so simply reducing the height isn't an option.

Thanks.

EDIT (Since apparently it's unclear what I'm asking)

Is there a way to prevent the height changing without using a script?

DEMO:

div {
  width: 200px;
  float: left;
  margin-right: 3px;
}
div img {
  max-width: 100%;
  max-height: 100%;
}
.div {
  border: 3px dotted blue;
  box-sizing: border-box;
}
<div id="div1">
  <img src="http://placehold.it/200x200" alt="" />
</div>
<div class="div">
  <img src="http://placehold.it/200x200" alt="" />
</div>
<div class="div" style="clear:left">
  <img src="http://placehold.it/200x200" alt="" />
</div>

Upvotes: 2

Views: 1362

Answers (3)

Banzay
Banzay

Reputation: 9470

Here is a variant of solution:

div {
    width:200px;
    float:left;
    margin-right:3px;
    box-sizing:border-box;
}
.div img {
    max-width:100%;
    max-height:100%;
    box-sizing: border-box;
    border:3px dotted blue;
}

Upvotes: 1

Vitorino fernandes
Vitorino fernandes

Reputation: 15951

You can set add line-height:0px if there is no text for .div as image is inline-block element it add whitespace

div {
  width: 200px;
  float: left;
  margin-right: 3px;
}
div img {
  max-width: 100%;
  max-height: 100%;
}
.div {
  border: 3px dotted blue;
  box-sizing: border-box;
  line-height:0px;
}
<div id="div1">
  <img src="http://placehold.it/200x200" alt="" />
</div>
<div class="div">
  <img src="http://placehold.it/200x200" alt="" />
</div>
<div class="div" style="clear:left">
  <img src="http://placehold.it/200x200" alt="" />
</div>

Upvotes: 3

Marawan Okasha
Marawan Okasha

Reputation: 448

Either add the line-height attribute to the div as @Vitorino suggested or add vertical-align: middle to the img. Both will fix the whitespace issue for an inline-block

div img {
  max-width: 100%;
  max-height: 100%;
  vertical-align: middle;
}
.div {
  border: 3px dotted blue;
  box-sizing: border-box;
  line-height:0px;
}

Upvotes: 1

Related Questions