DGA DGA - 5 months ago 9
CSS Question

Fix a Responsive Image

I would like this image to reach only 500px of height for a responsive web site.
The problem is I need several parts like this in a web site that I am making, but can't make it to fix good with every viewport.



*,
*:before,
*:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.html,body {
margin: 0;
padding: 0;
font-family: 'Lato', sans-serif;
font-size: 62.5%;
}


.bigImages {
display: block;
max-width: 100%;
height: auto;
}

@media (min-width:1400px) {
.bigImages {
width: 100%;
height: 500px;
}
}





.highlightText3 {
font-family: $fontLatoHeavy;
font-size: 8rem;
line-height: 1.4;
text-align: center;
color: #000;
z-index: 10;
padding: 100px 0 100px 0;
background: rgb(66,
133,
244);;
}

<link href='https://fonts.googleapis.com/css?family=Lato:700' rel='stylesheet' type='text/css'>
<h2 class="highlightText3">SERVICES</h2>
<img class="bigImages" src="https://images.unsplash.com/photo-1465152251391-e94453ee3f5a?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=2f3699fc4dbc682fbecdc4fa4d5f6cad">




Answer

If you can, wrap the image in a container. This way you can constrain the area the image takes up and mask it as needed:

<h2 class="highlightText3">SERVICES</h2>
<figure class="image-wrapper">
  <img class="bigImages" src="https://images.unsplash.com/photo-1465152251391-e94453ee3f5a?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=2f3699fc4dbc682fbecdc4fa4d5f6cad" alt="Surfing a big wave">
</figure>

I styled the image-wrapper to have a fixed, 500px height. I then positioned the image absolute so I can push it around and center it. Lastly, I added an aspect-ratio media query to flip how the image is constrained and allow it to scale nicely across all viewport sizes (though the h2 still needs some love on the smaller viewports):

.image-wrapper {
  display: block;
  height: 500px;
  overflow: hidden;
  position: relative;
}

.bigImages {
    display: block;
    height: auto;
    width: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

@media screen and (max-aspect-ratio: 4/3) {
  .bigImages {
      height: 100%;
      width: auto;
  }
}

Demo here: https://jsfiddle.net/0o2ykLh7/

Comments