I have two divs within a container. One floats left and one floats right. Both are about 60% as wide as the container and are designed such that they overlap in the middle (right div takes priority).
How do I get them to overlap rather than stack vertically like floating elements usually do? If I absoultely position the right element the containing div doesn't expand to fit the content.
Code (unfortunately I cannot jsfiddle this as their servers are read only atm):
<div id="container"> <div id="left">left</div> <div id="right">right</div> </div> #container { width: 400px; background-color: #eee; } #left { width: 250px; border: 1px solid #ccc; display: inline; float: left; } #right { width: 250px; border: 1px solid #ccc; display: inline; float: right; }
You can use the CSS position property in combination with the z-index property to overlay an individual div over another div element. The z-index property determines the stacking order for positioned elements (i.e. elements whose position value is one of absolute , fixed , or relative ).
To overlap or layer HTML elements: Set the position of the elements to relative , absolute , or fixed . Then, use z-index to specify which element is on top or below.
You can apply the CSS position:relative; and then specify an offset such as top:-50px;left:-20px; which would shift the element 20 pixels to the left and 50 pixels up. You can also specify right and bottom and use positive or negative values.
If you need more precise overlap control for multiple elements, assign specific z-index values to your elements, the higher the value the more on top the element will be. You can also use minus values.
Use a negative margin-right
on the left box so that the right box is allowed to overlap:
#left { width: 250px; border: 1px solid #ccc; display: inline; float: left; margin-right:-104px; }
The 104 pixels is the overlap amount plus 4px for borders.
Here's a jsfiddle.
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