I want to put a side bar on top of an image, with the same width as the image. Neither width: inherit|100% work.
CSS
body {
display: flex;
}
#main-pic {
width: 40%;
height: 700px;
}
#main-pic>img {
width: 100%;
height: 100%;
}
#logo-holder {
width: inherit;
height: 100px;
background-color: brown;
position: absolute;
top: 50%;
}
HTML
<div id="main-pic">
<img src="myFlower.JPG" alt="My Flower">
<div id="logo-holder"></div>
</div>
<div id="main-text">
<p>This is the part for text</p>
</div>
In this example, I use width: inherit, the #logo-holder is a bit longer than the image. I tried width: 100%, it's stretched across browser. Can someone explain and suggest a solution?
You need to assign position: relative
to the #main-pic
element, so its children could use its relative dimensions properly:
body {
display: flex;
}
#main-pic {
width: 40%;
height: 700px;
/* added */
position: relative;
}
#main-pic>img {
width: 100%;
height: 100%;
}
#logo-holder {
width: 100%;
height: 100px;
background-color: brown;
position: absolute;
top: 50%;
}
<div id="main-pic">
<img src="https://picsum.photos/id/42/400/800" alt="My Flower">
<div id="logo-holder"></div>
</div>
<div id="main-text">
<p>This is the part for text</p>
</div>