0

I am using css grid .I want to show my image using aspect ratio. depending upon width I want to show image .I don't want to give hard corded value of height .is it possible to show image without giving height .?In other words I depending upon width I want to show image without giving any value of height .

here is my code

https://codesandbox.io/s/condescending-flower-m616l?file=/index.html

          .abc {
            display: grid;
            grid-template-columns: repeat(12, 6.697%);
            grid-template-rows: 18px repeat(4, 1fr);
            border: 1px solid green;
            height: 320px;
          }
          .one {
            grid-column: 2/5;
            grid-row: 3/5;
            border: 1px solid;
          }
          .two {
            grid-row: 1/5;
            grid-column: 2/5;
            border: 1px solid #ee0;
          }
          .two div {
            max-width: 100%;
            /* height: 100%; */
          }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Static Template</title>
        
      </head>
      <body>
        <div class="abc">
          <div class="one">
            <p>
              Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates
              culpa iste facaudantium Lorem ipsum,
            </p>
          </div>
          <div class="two">
            <div style="background-image: url('hero.png');"></div>
          </div>
        </div>
      </body>
    </html>

I am giving /* height: 100%; */ then only my image display ?

BeerusDev
  • 1,444
  • 2
  • 11
  • 30
user944513
  • 12,247
  • 49
  • 168
  • 318
  • Just use `transform: scale();` instead – Rojo Sep 07 '21 at 18:45
  • from your code, div 1 and 2 are overlapping each others, are we supposed to see the text over the image ? Maybe a screen of expected result would explain what you are trying to achieve and how you are failing (background-size + aspect-ratio might also be missing from your code. – G-Cyrillus Sep 07 '21 at 18:57

1 Answers1

1

Use the CSS aspect-ratio property to set an aspect ratio to the div of the image.

.two div {
  aspect-ratio: 1 / 1;
  background-size: cover;
}

Though at the moment of writing aspect-ratio is not yet supported by all major browsers. caniuse.com - aspect-ratio.

As a fallback, use the padding hack with a pseudo element.

@supports not (aspect-ratio: 1 / 1) {
  .two {
    position: relative;
  }

  .two::before {
    content: "";
    display: block;
    padding-top: 100%; /* This will give it the same height as width. */
  }

  .two div {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32