Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Make two floating elements overlap

Tags:

html

css

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; } 
like image 933
Chris Avatar asked Feb 10 '12 11:02

Chris


People also ask

How do you make two elements overlap CSS?

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 ).

How do I enable overlap in CSS?

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.

How do you overlap elements in HTML?

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.

How do you control overlap in CSS?

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.


1 Answers

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.

like image 139
Gareth Avatar answered Sep 24 '22 22:09

Gareth