I have a container which has the height of 100vh
. It contains an image and some text. The height of the text can change based on the screen and text. I want the text to take up the space that it needs and the image should use the rest of the available space.
Here is my code. It is already what I want basically but I want to get rid of the 83vh
. The image should take the rest of the space dynamically. Is this possible?
Thank you guys!
PS: I added the Javascript tag because I'm not sure if a Javascript solution might be necessary.
.container {
height: 100vh;
max-height: 100vh;
background-color: #CCCCCC;
}
img {
max-height: 100%;
width: 100%;
object-fit: cover;
object-position: center -180px;
/* this height should be dynamically */
height: 83vh
}
.text-wrapper {
padding-left: 15px;
}
<div >
<img src="https://img.100r.systems/img/be10bc26de653473f80b4348addfc6b5.jpg">
<div >
<h1>Some Text goes here</h1>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor <br>invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</div>
</div>
CodePudding user response:
You could achieve this by using CSS grid. The two cells in the grid being of 1fr (ie as much space as is left) and auto in height.
This snippet also moves the img to be a background-image within a div, covering its cell and centered.
* {
margin: 0;
}
.container {
position: relative;
height: 100vh;
width: 100vw;
rmax-height: 100vh;
background-color: #CCCCCC;
display: grid;
grid-template-rows: 1fr auto;
grid-template-columns: 1fr;
}
.img {
width: 100%;
height: 100%;
background-size: cover;
background-position: center center;
background-image: url(https://img.100r.systems/img/be10bc26de653473f80b4348addfc6b5.jpg);
}
.text-wrapper {
padding-left: 15px;
}
<div >
<div ></div>
<div >
<h1>Some Text goes here</h1>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor <br>invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</div>
</div>
Note: for a completely general solution you need to decide what should happen if the text itself takes up more than the height of the viewport.
CodePudding user response:
I think I did it
.container {
height: 100vh;
max-height: 100vh;
background-color: #CCCCCC;
display: flex;
flex-flow: column;
height: 100%;
}
.image-wrapper {
flex: 1 1 auto;
max-height: 100%;
overflow: hidden;
}
img {
max-height: 100%;
width: 100%;
object-fit: cover;
object-position: center -180px;
}
.text-wrapper {
padding-left: 15px;
flex: 0 1 auto;
}
<div >
<div >
<img src="https://img.100r.systems/img/be10bc26de653473f80b4348addfc6b5.jpg">
</div>
<div >
<h1>Some Text goes here</h1>
<p>I think it works now<br> and I'm very happy now<br>It works, right?
</div>
</div>