Master DJon Master DJon - 3 months ago 18
Javascript Question

Center a DIV containing relative element using CSS

I struggle about this behavior. I add two DIVs (sub1 and sub2) inside a DIV container. Sub2 is set a relative position to overlap the bottom right corner of the Sub1. Doing this, the width of the container DIV isn't good, it is the same as before changing relative position of Sub1. At first, it wasn't problematic, but then, the client decided to center the whole thing, thus needing the real width of the container.

Can this be achieved via CSS ? Even in JavaScript, I got the same width (the erronus one).

Here is the a simple example of the problem :



html, body {
width:100%;
height: 100%;
}

#main {
position: fixed;
display: inline-block;
margin: auto;
}

#sub1 {
width: 100px;
height: 100px;
background-color:red;
position: relative;
}

#sub2 {
width: 100px;
height: 100px;
background-color: blue;
position: relative;
left: 80px;
top: -20px;
}

<div id="main">
<div id="sub1">
</div>
<div id="sub2">
</div>
</div>




Answer

If you want your container DIV to possess width of two blocks you shouldn't use relative positioning. Use margin instead

#sub2 {
  width: 100px;
  height: 100px;
  background-color: blue;
  margin-left: 80px;
  margin-top: -20px;
}
Comments