Jad Chahine Jad Chahine - 1 month ago 4
CSS Question

How to overlap divs using CSS?

What I have is a user profile container that contains a head, a body (with two inner body section) and a footer that contains a photo.

enter image description here

I am looking for a way to make the divs overlapped so the first div at the left will be fixed and each next div will be overlap on the previous one like this one:

enter image description here

Here what I have

HTML

<div class="userContainer">
<div class="userHead">
Head
</div>
<div class="userBody">
<div class="userBody1">
Body 1
</div>
<div class="userBody2">
Body 2
</div>
<div class="userImage">
<img src="https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg">
</div>
</div>
</div>

<div class="userContainer">
<div class="userHead">
Head
</div>
<div class="userBody">
<div class="userBody1">
Body 1
</div>
<div class="userBody2">
Body 2
</div>
<div class="userImage">
<img src="https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg">
</div>
</div>
</div>


CSS

.userContainer {
position: relative;
float: left;
margin-right: 20px;
color: white;
height:100px !important;
}

.userHead {
background-color: #f05624;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
font-size: 14px;
color: white;
border-radius: 200px;
margin-left: 20px;
font-weight: 400;
}

.userBody {
width: 75px;
position: absolute;
top: 30px;
left: 3px;
border-top-right-radius: 150px;
border-top-left-radius: 150px;
border-bottom-right-radius: 20px;
border-bottom-left-radius: 20px;
font-weight: 400;
text-align: center;
}

.userBody1 {
height: 25%;
border-top-right-radius: 150px;
border-top-left-radius: 150px;
background-color: #f05624;
padding-top: 10px;
}

.userBody2 {
height: 15%;
background-color: #f05624;
font-size: 10px !important;
}

.userImage img{
height: 100%;
width: 100%;
}


Check jsfiddle

Any suggestions?

Answer

Add another line of css, explicilty setting the first containers left margin to 0 px.

.userContainer:nth-child(1){
    margin-left:0px;
}

Set your other container margins to margin-left -20px

.userContainer {
    position: relative;
    float: left;
    margin-right: 20px;
    color: white;
    height:100px !important;
    margin-left:-30px;
}

Here is an example:

https://jsfiddle.net/edqpyvs1/2/

Updated solution:

Add this JS code to make sure that the container has a greater z-index that the next container etc...

var containers = document.getElementsByClassName("userContainer");

var zindexvalue = 1000;

for(index = containers.length - 1 ; index >= 0; index--){
  var container = containers[index];
  container.style.zIndex = zindexvalue;
  zindexvalue = zindexvalue + 1;
}

Check it out.

Comments