首页 > 解决方案 > How can I display html image in a container the same way css displays background-image?

问题描述

So I have this div where I want to display an html image at a dimension of 1200 by 630. The images are usually smaller than the container. If I display the image by using CSS's background-image, background-size and background-position then a smaller-sized image gets fitted in the container by scaling up(zoomed in).

This is what I've been trying to achieve by using an image in html. Please note that I can't use object-fit because I'll be using this image with a plugin that doesn't support object-fit css property.

This is the CSS version:

.outer {
  width: 1200px;
  height: 630px;
}

#div {
  background-image: url('https://i.imgur.com/dqywpKM.jpg');
  background-position: center center;
  background-size: cover;
  width: 100%;
  height: 100%;
}
<div class="outer">
  <div id="div">
  </div>
</div>

This is the HTML Image version:

.outer {
  width: 1200px;
  height: 630px;
}

#div {
  background-color: white;
  width: 100%;
  height: 100%;
}

#img_prev {
  height: 100%;
  width: 100%;
  background-size: cover;
  background-position: center center;
}
<div class="outer">
  <div id="div">
    <img src="https://i.imgur.com/dqywpKM.jpg" id="img_prev" />
  </div>
</div>

The HTML image version looks slanted but I have been trying to make it look like a little bit zoomed to fit the container without using object-fit. How can I do that?

标签: htmlcss

解决方案


enter code here

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
    <div class="outer">
        <div id="div">
        </div>
    </div>

    <style>

        .outer {
            width: 1200px;
            height: 630px;
        }
          
        #div {
            background-image: url('https://images.unsplash.com/photo-1610128114197-485d933885c5?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80');
            background-position: center;
            background-size: cover;
            background-repeat: no-repeat;
            background-attachment: fixed;
            width: 100%;
            height: 100%;
        }
    </style>
</body>
</html>


推荐阅读