HTML Element Style How to - Use div background to show single image








Question

We would like to know how to use div background to show single image.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.img {<!--   w ww  . j a  v a2s  .c om-->
  overflow: hidden;
  border: 1px solid black;
  width: 300px;
  height: 200px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.img1 {
  background-image:url('http://www.java2s.com/style/download.png');
}

.img2 {
  background-image:url('http://www.java2s.com/style/download.png');
}
</style>
</head>
<body>
  <h2>Portrait Image</h2>
  <div class="img img1"></div>
  <h2>Landscape Image</h2>
  <div class="img img2"></div>
</body>
</html>

The code above is rendered as follows: