skip to Main Content

I’m trying to create a responsive image using HTML and CSS. What I am trying to achieve is, as the screen size reduces, the right side of the image to crop to maintain the height and position of the image. A reference to this is how nikes hero image is.The reason for this style is-just like on the nike website I have white space to the left and right side of my image. I want to preserve the white space when the screen is being resized.How do I achieve this? I am attaching part of my code below

.hero {
  position: relative;
  text-align: center;
  top: 6.7rem;
  width: 100%;
}

.hero>img {
  width: 100%;
  max-width: 1330px;
  height: 690px;
  object-fit: cover;
}
<div class="hero">
  <img src="https://static.nike.com/a/images/q_auto:eco/t_product_v1/f_auto/dpr_2.0/w_441,c_limit/9d1635ed-eed0-45b0-b34d-e00468e2f79e/tanjun-easyon-shoes-mplG1H.png" alt="">
</div>

2

Answers


  1. Use max-height instead of fixed height to avoid croping

    I have used another image because nike site is blocked in my network

    .hero {
      position: relative;
      text-align: center;
      top: 6.7rem;
      width: 100%;
    }
    
    .hero>img {
      width: 100%;
      max-width: 1330px;
      max-height: 690px;
      object-fit: cover;
    }
    <div class="hero">
      <img src="https://3.img-dpreview.com/files/p/TS1200x900~sample_galleries/0740273820/4223361595.jpg" alt="">
    </div>
    Login or Signup to reply.
  2. To create a responsive image that maintains its height and crops the right side as the screen size reduces, you can use CSS and the object-fit property, similar to what you’ve started with. However, you also need to adjust the container’s size to maintain the desired aspect ratio.

    Here’s an example of how you can achieve this effect:

    <style>
    .hero {
      position: relative;
      text-align: center;
      width: 100%;
      max-width: 1330px; /* Set your desired max width */
      margin: 0 auto; /* Center the container horizontally */
      overflow: hidden; /* Hide overflowing content */
     }
    
     .hero img {
      width: 100%;
      height: auto; /* Let the image determine its own height */
      object-fit: cover; /* Crop the image to cover the container */
     }
     </style>
    
     <div class="hero">
       <img src="https://static.nike.com/a/images/q_auto:eco/t_product_v1/f_auto/dpr_2.0/w_441,c_limit/9d1635ed-eed0-45b0-b34d-e00468e2f79e/tanjun-easyon-shoes-mplG1H.png" alt="">
     </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search