2

How can I ensure that the img within the container is centered and scaling correctly from mobile to desktop? Here is a demo on Codepen. Scale to mobile to better understand the problem

HTML

<div class="image-container">
  <img src="https://placeimg.com/470/310/people" alt="" /> 
</div>

CSS

.image-container{
 width: 100%;
 height: 500px;
 max-height: 500px;
 background: red;
 overflow: hidden;
 text-align: center;
 position: relative;
 display: block;
 }

 img{
 height: auto;
 width: 100%;
 max-width: 100%;
 position: absolute;
 top: -50%;
 left: 0;
}

I ask this because the image loses it height on mobile and looks incorrect. I sort of what this to work like `background-size: cover. I'd like the image to completely fill the container

Samuel
  • 5,529
  • 5
  • 25
  • 39

2 Answers2

0

To center image horizontally and vertically inside div you can set top: 50% and left: 50% and then just add transform: translate(-50%, -50%).

To make image responsive you can use max-width: 100% and by default height is auto.

.image-container {
  width: 100%;
  height: 500px;
  background: red;
  overflow: hidden;
  position: relative;
}
img {
  max-width: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="image-container">
  <img src="https://placeimg.com/470/310/people" alt="" />
</div>

Other option is to use Flexbox if you don't want to use relative/absolute position but to keep img responsive you can use object-fit: contain with height: 100%

.image-container {
  width: 100%;
  height: 500px;
  background: red;
  display: flex;
  align-items: center;
  justify-content: center;
}

img {
  max-width: 100%;
  object-fit: contain;
}
<div class="image-container">
  <img src="https://placeimg.com/470/310/people" alt="" />
</div>

If you want img to behave like background-size: cover one way to that is to use object-fit: cover with height: 100% and width: 100%

body,
html {
  margin: 0;
  padding: 0;
}
.image-container {
  width: 100%;
  height: 500px;
  background: red;
  display: flex;
  align-items: center;
  justify-content: center;
}
img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="image-container">
  <img src="https://placeimg.com/470/310/people" alt="" />
</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • To be honest i'm fairly new to flexbox. I used your code within my Bourbon grid and it did not work. – Samuel Jun 29 '16 at 17:35
0

You can add margin:0 auto; to align center horizontally. Remove width:100% as this will stretch width of an image unless you want it to. Keep height:auto to adjust with width.

.image-container{
  width: 100%;
  height: 500px;
  max-height: 500px;
  background: red;
  overflow: hidden;
  text-align: center;
  position: relative;
  display: block;
}

img{
 height: auto;
 max-width: 100%;
 margin:0 auto;
}
<div class="image-container">
  <img src="https://placeimg.com/470/310/people" alt="" />
</div>
Rohit
  • 1,794
  • 1
  • 8
  • 16