How to Center an Image Between the Containers

It is now a common question “How to make the image responsive and keep it in between the containers”. Follow the given steps to solve this problem.

1. Create HTML

  • Create 3 <div> elements with classes "left", "right" and "center".
  • Copy and paste the link of the image you want to center between right and left containers.
<div class="left"></div>
<div class="right"></div>
<div class="center">
  <img src="https://images.unsplash.com/photo-1542546068979-b6affb46ea8f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80">
</div>

2. Create CSS

  • Set the background-color for both right and left containers.
  • Define the width and the height of containers.
  • Make the elements float to left and right with the float property.
.left {
background-color: #de6502;
width: 150px; 
height: 800px;
float: left;
}
.right {
background-color: #1c87c9;
width: 150px;
height: 800px;
float: right;
}
  • Set the height, background-color for the middle container.
  • Set the overflow to "hidden".
.center {
height: 800px;
background-color: #cccccc;
overflow: hidden;
}

So, here’s the full code:

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      body {
      background-color: #ffffff;
      }
      .div1 {
      background-color: #de6502;
      width: 150px;
      height: 600px;
      float: left;
      }
      .div2 {
      background-color: #1c87c9;
      width: 150px;
      height: 600px;
      float: right;
      }
      .div3 {
      height: 600px;
      background-color: #cccccc;
      overflow: hidden;
      text-align: center;
      }
      img {
      max-width: 100%;
      height: auto;
      }
    </style>
  </head>
  <body>
    <div class="div1"></div>
    <div class="div2"></div>
    <div class="div3">
      <img src="https://images.unsplash.com/photo-1542546068979-b6affb46ea8f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80">
    </div>
  </body>
</html>

Do you find this helpful?

Related articles