Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crop an image when height limit is reached? using html and css

i have an image that is kind of large and in order for it to not take up all the screen on wider devices i want it to appear cropped from the top and bottom when a certain height limit is reached, e.g. 600px. This isnt a problem on smaller, narrower screens since the image scales down and doesnt cover the other parts of my webapp. thanks in advance!

this is what ive currently got:

HTML:

  <div class="image-container">
    <img src="../../assets/home_image1.jpg" alt="bg image of airplane" class="background-image" />
    <div class="text-overlay">
      <h1>Universal Tours</h1>
    </div>
  </div>

CSS:

.image-container {
  position: relative;
  text-align: center;
}

.background-image {
  width: 100%;
  height: auto;
  display: block;
}

.text-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.5); /* Optional background color */
  padding: 10px;
  color: #fff; /* Text color */
  border-radius: 5px; /* Optional border-radius */
}

ive tried height limit but it shrinks the image keeping the aspect ratio, and that leaves empty space around it and doesnt look very good.

like image 852
Kenzo Avatar asked Dec 21 '25 06:12

Kenzo


1 Answers

You can use the CSS property object-fit: cover; along with setting a maximum height.

.image-container {
  position: relative;
  text-align: center;
  overflow: hidden; /* hides extra parts of image */
  max-height: 600px; /* max height */
}

.background-image {
  width: 100%;
  height: 100%; /* sets height = 100% of the container */
  object-fit: cover; /* will make sure image covers the area and is cropped */ 
}
like image 200
Daqs Avatar answered Dec 23 '25 20:12

Daqs