Vertically and horizontally centered image in a div only with css

In this example below you will see how to do a Vertically and horizontally centered image in a div only with css with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by sergiopedercini, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright sergiopedercini ©
  • HTML
  • CSS
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Vertically and horizontally centered image in a div only with css</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="container">
  <img alt="Alt text" src="http://pipsum.com/435x310.jpg" />
</div>
<div class="container">
  <img alt="Alt text" src="http://pipsum.com/200x310.jpg" />
</div>
  
  

</body>

</html>

/*Downloaded from https://www.codeseek.co/sergiopedercini/vertically-and-horizontally-centered-image-in-a-div-only-with-css-aBBZOx */
.container {
  position: relative;
  width: 200px;
  height: 200px;
  margin: 20px auto;
  background: tomato;
  overflow: hidden;
}
.container img {
  display: block;
  position: absolute;
  max-width: 100%;
  max-height: 100%;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%);
}

Comments