Here is the HTML I am working with.
<div id="outer" style="min-width: 2000px; min-height: 1000px; background: #3e3e3e;"> <div id="inner" style="left: 1%; top: 45px; width: 50%; height: auto; position: absolute; z-index: 1;"> <div style="background: #efffef; position: absolute; height: 400px; right: 0px; left: 0px;"></div> </div> </div>
What I would like to happen is for the inner div to occupy 50% of the space given to its parent div(outer). Instead, is is getting 50% of the space available to the viewport, which means that as the browser/viewport shrinks in size, so does it.
Given that the outer div has min-width
of 2000px
, I would expect the inner div to be at least 1000px
wide.
In this case, we set the child element's width to be 100% of the viewport width by using a percentage viewport unit (vw), then, we move it to the left side (by the distance of the viewport's half, minus 50% of the width of the parent element) with the left property.
Method 2: We can make the display attribute of the child container to table-row and display attribute of parent container to table, that will take all the height available from the parent div element. To cover all the width, we can make the width of parent div to 100%.
One way you can achieve this is setting display: inline-block; on the div . It is by default a block element, which will always fill the width it can fill (unless specifying width of course).
Try It: Set the width of an image using a percentage and resize your browser window. For the width attribute, you can also use percentages, where 100% is the total space available. So, if you wanted an image to be one quarter the width of the window, you could set width to 25% (one quarter of 100% is 25%).
Specifying a non-static position, e.g., position: absolute/relative
on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/
See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts
We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.
#outer { min-width: 2000px; min-height: 1000px; background: #3e3e3e; position:relative } #inner { left: 1%; top: 45px; width: 50%; height: auto; position: absolute; z-index: 1; } #inner-inner { background: #efffef; position: absolute; height: 400px; right: 0px; left: 0px; }
<div id="outer"> <div id="inner"> <div id="inner-inner"></div> </div> </div>
Use position: relative on the parent element.
Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With