Tino Tino -3 years ago 94
CSS Question

Resize Images, keeping ratio, html?

I am trying to resize a background picture to fit in a div. The problem I have is that I want the image to fit the height of the div and keep ratio. For example, I have a div which I don't want it to grow further the width of the screen (to prevent scrolling bars from appearing) and the image that I want to use is 1024px X 400px. If I try to fit the height of the image, It will force the width to fit also and it will lose ratio. I dont care if parts of the image are not shown. In fact, that is what I want to do.

What tags do I need to use? HTML5 or CSS

Answer Source

Use CSS background-size: cover; to fill the <div>, or background-size: auto 100%; if you just want to match the height and don't care if the sides over- or under-flow:

html,
body {
  position: relative;
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

div {
  background-image: url(https://placebear.com/1024/400.jpg);
  display: inline-block;
  background-repeat: no-repeat;
  border: 1px solid black;
}

.cover {
  background-size: cover;
}

.center {
  background-position: center;
}

.height {
  background-size: auto 100%;
}
<h1>Unstyled</h1>
<div style="width: 50px; height: 200px"></div>
<div style="width: 200px; height: 50px"></div>
<div style="width: 125px; height: 125px"></div>

<h1>Un-centered</h1>
<h2>Cover</h2>
<div class="cover" style="width: 50px; height: 200px"></div>
<div class="cover" style="width: 200px; height: 50px"></div>
<div class="cover" style="width: 125px; height: 125px"></div>

<h2>100% Height</h2>
<div class="height" style="width: 50px; height: 200px"></div>
<div class="height" style="width: 200px; height: 50px"></div>
<div class="height" style="width: 125px; height: 125px"></div>

<h1>Centered</h1>
<h2>Cover</h2>
<div class="cover center" style="width: 50px; height: 200px"></div>
<div class="cover center" style="width: 200px; height: 50px"></div>
<div class="cover center" style="width: 125px; height: 125px"></div>

<h2>100% Height</h2>
<div class="height center" style="width: 50px; height: 200px"></div>
<div class="height center" style="width: 200px; height: 50px"></div>
<div class="height center" style="width: 125px; height: 125px"></div>

In addition, use background-position: center; if you want to crop the image so that the center is always the focus instead of the top-left.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download