Home > Net >  What is the best way to move two HTML elements around on a page with CSS so they overlap?
What is the best way to move two HTML elements around on a page with CSS so they overlap?

Time:02-27

Whenever I want to be able to make two things overlap (like an image over another image or something), using margin or padding works but it can make other things not work properly (like text not going to the next line or not being able to make other things overlap anymore). I want to know this for future use in any project, not really a specific one so I don't have a code snippet.

CodePudding user response:

I would go with position: relative for both (or at least one of the) elements in question.

That does not affect the position of the other elements of that document, because is isn't removing the elements from the normal document flow.

The overlap of the relatively positioned elements is then realized by offsetting each of them relative to itself based on the values of top, right, bottom, and left.

CSS to make 2 divs overlap vertically 10px:

div {
  border: 1px solid red;
}

.overlap {
  position: relative;  
}

.overlap.one {
  bottom: -5px;
}

.overlap.two {
  top: -5px;
}
<div>Before</div>
<div >Div One - without overlap</div>
<div >Div Two - without overlap</div>
<div>After</div>
<hr>
<div>Before</div>
<div >Div One - overlapping downwards</div>
<div >Div Two - overlapping upwards</div>
<div>After</div>
<hr>

  • Related