I have been struggling with this problem for a couple of weeks now. I have a container which is 90vh. I have some header text and below it is an image. I need to maintain the aspect ratio of 16:9. But, the height must never exceed the height of the container causing scrollbar to appear. Is it doable??
Here is the calculation for 16:9 aspect ratio
To get height base on width (9 * WIDTH) / 16;
To get width base on height (16 * HEIGHT) / 9
https://codesandbox.io/s/sleepy-sara-ew3oj9?file=/src/styles.css
CodePudding user response:
the .wrapper
element never exceed the height of the container, because 90vh
isn't working.
❌ the part which is wrong
height: "90vh"; /* turn this from string to number, without this "" */
✅ make it like this:
height: 90vh;
also for the aspect-ratio problem,
you can a native css solution, called aspect-ratio
img {
aspect-ratio: 16/9;
width: 100%;
}
with this solution, the image will be always 100%,
but the height change depends on aspect-ratio
.App {
font-family: sans-serif;
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.container {
padding: 1rem;
margin: 1rem;
}
.content {
display: grid;
grid-template-columns: 80% 20%;
margin-top: 2rem;
gap: 1rem;
}
.wrapper {
height: 90vh;
/* turn this from string to number, without this "" */
border: 1px solid;
margin: 1rem;
}
.sidebar {
border: 1px solid;
}
.content img {
aspect-ratio: 16/9;
width: 100%;
}
<div >
<div >
<div >
<div >
<h1>Here is header</h1>
<p>Here is sub header</p>
</div>
<div >
<img alt="Hello" src="https://images.unsplash.com/photo-1611771341253-dadb347165a8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8YmVhdXRpZnVsJTIwbmF0dXJlfGVufDB8fDB8fA==&auto=format&fit=crop&w=500&q=60" />
<div >Side bar</div>
</div>
<!-- content -->
</div>
<!-- container -->
</div>
<!-- wrapper -->
</div>
<!-- app -->
CodePudding user response:
Set max-width on your image, to force it to take the size of the grid you defined. Also set a height 100% on your .container
class
img {
max-width: 100%;
max-height: 100%;
}