Resize images, save ratio, html?

I am trying to resize the wallpaper to fit in a div. The problem is that I want the image to fit the height of the div and keep relationship. For example, I have a div that I don’t want it to expand to fit the width of the screen (so that scrollbars do not appear), and the image I want to use is 1024px X 400px. If I try to set the height of the image, it will make the width also fit, and it will lose the ratio. I do not like it if parts of the image are not displayed. In fact, this is what I want to do.
What tags do I need to use? HTML5 or CSS

+6
source share
2 answers

Use CSS background-size: cover;to fill in <div>or background-size: auto 100%;if you just want to combine height and don’t care if the sides are excessive or under the stream:

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>
Run codeHide result

Also, use background-position: center;if you want to crop the image so that the center is always the focus, not the top left.

+5
source

If you can lower the threshold a little, you can also use:

img {
  width: 100vw;
  height: 100vh;
  max-width: 100%;
  max-height: 100%;
}
+1
source

All Articles