scriver
scriver

Reputation: 85

How to center an image between the containers?

How do I make the image responsive and keep it in between the containers left and right.

I have tried putting it all into another container and it doesn’t work.

I know it sounds basic but it really is not.

body {
  background-color: black;
}

.left {
  background-color: red;
  width: 150px;
  height: 800px;
  float: left;
}

.right {
  background-color: green;
  width: 150px;
  height: 800px;
  float: right;
}

img {
  display: block;
  margin-left: auto;
  margin-right: auto;
}
<div class="left"></div>
<div class="right"></div>
<img src="paintingOg.gif" style="width:50%">

Upvotes: 0

Views: 114

Answers (2)

Razvan Zamfir
Razvan Zamfir

Reputation: 4686

How about this way? Is it (close to) what you need? Please check responsiveness too.

body {
  background-color: black;
}

.left {
  background-color: red;
  width: 150px;
  height: 800px;
  float: left;
}

.right {
  background-color: green;
  width: 150px;
  height: 800px;
  float: right;
}

.center {
  height: 800px;
  background-color: blue;
  overflow: auto;
  text-align: center;
}

img {
  max-width: 100%;
  height: auto;
}
<div class="left"></div>
<div class="right"></div>
<div class="center">
  <img src="https://picsum.photos/500/500?gravity=west">
</div>

Upvotes: 3

Synapsis
Synapsis

Reputation: 1017

You don't need containers to center something. It's better to use 1 container that contains everything. If you want to center your image into a div just use this code:

<div align="center">
    <image src="whatever.png"/>
</div>

body {
  background-color: black;
}

.left {
  background-color: red;
  width: 150px;
  height: 800px;
  float: left;
}

.right {
  background-color: green;
  width: 150px;
  height: 800px;
  float: right;
}

img {
  width: 100%;
  height: auto;
}
<div class="left"></div>
<div class="right"></div>
<div align="center">
<img src="paintingOg.gif" />
</div>

Upvotes: 1

Related Questions