I want the '.box' to be 33% of height. However, trying to set it below, doesn't work. It a container box, meaning it holds an image and a text hovering over the image. When the box is at 33%, I want the image to crop down and show only 33% of it.
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=placing-text-over-an-image-with-css
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of Text Block Over Image</title>
<style>
.box{
margin-top: 100px;
width: 100%;
height: 33%;
position: relative;
}
.box .text{
position: absolute;
z-index: 2;
text-align: center;
top: 0;
background: rgba(0, 0, 0, 0.8);
color: #fff;
height: 100%;
width: 100%; /* Set the width of the positioned div */
}
.img {
width: 100%;
}
</style>
</head>
<body>
<div class="box">
<img class="img" src="/examples/images/kites.jpg" alt="Flying Kites">
<div class="text">
<h1>Flying Kites</h1>
</div>
</div>
</body>
</html>
CodePudding user response:
Both the html element and body element have their height CSS property set to auto by default. This means that they do not have an explicit height. They will grow to be as tall as it's content. This is why height: 33%
on the child of the body will have no effect.
In this case, if you want to get the height of 33% of the height of the document, you can use height: 33vh
instead.
So I would change your example code to this. Because you want to only show 33% of the image, I would add overflow: hidden
.box{
position: relative;
display: inline-block; /* Make the width of box same as image */
height: 33vh;
overflow: hidden;
}
CodePudding user response:
body{height: 100vh;}
.box{
margin-top: 100px;
width: 100%;
height: 33%;
position: relative;
overflow: hidden;
}
.box .text{
position: absolute;
z-index: 2;
text-align: center;
top: 0;
background: rgba(0, 0, 0, 0.8);
color: #fff;
height: 100%;
width: 100%; /* Set the width of the positioned div */
}
.img {
width: 100%;
}
<div class="box">
<img class="img" src="https://cdn.pixabay.com/photo/2021/08/25/20/42/field-6574455__480.jpg" alt="Flying Kites">
<div class="text">
<h1>Flying Kites</h1>
</div>
</div>
CodePudding user response:
In order this to work, the .box's parent should have a height. body is the parent of .box , so you should give it a height of 100vh.
body {
height: 100vh;
}
everything else is fine.