Home > Enterprise >  Overlapping two boxes
Overlapping two boxes

Time:04-30

I have been trying to have two boxes in CSS, one in the upper right hand corner of the other. I have been trying to nest divs and use relative positioning but I cannot figure out how to do it. Can someone help me? (Not using z index)

CodePudding user response:

If I understand correctly that you want one box to be inside the other, you can achieve this using position: relative and moving the inner box using top, right, left and bottom.

I recommend diving in to the MDN page for CSS position for more information.

.box1, .box2 {
  display: inline-block;
}

.box1 {
  width: 200px;
  height: 200px;
  background: green;
}

.box2 {
  position: relative;
  width: 100px;
  height: 100px;
  top: -100px;
  left: -100px;
  background: orange;
}
<div class='box1'></div>
<div class='box2'></div>

CodePudding user response:

You can use something like this. Using flexBox to align them and giving a negative margin to second box.

*,
*::before,
*::after {
  box-sizing: border-box;
}


body {
  min-height: 100vh;
  margin: 0;
  background-color: bisque;
  display: grid;
  place-content: center;
}

.container{
  display: flex;
  flex-direction: row;
}
.first{
  height: 5rem;
  width: 5rem;
  background-color: tomato;
}
.second{
  margin-top:-50%;
  height: 5rem;
  width: 5rem;
  background-color: tomato;
}
<div >
      <div ></div>
      <div ></div>
</div>

Based on Marcos answer i think i understand you wrong.

Here is a simple way get the result that you want. You can use position:relative to parent and position: absolute to child item. Then you can move child element inside. top:0; will take you to top corner and right:0; will take you to right corner.

*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  margin: 0;
  background-color: bisque;
  display: grid;
  place-content: center;
}

.parent{
  width: 10rem;
  height: 10rem;
  background-color: tomato;
  position: relative;
}

.child {
  width: 5rem;
  height: 5rem;
  background-color: aqua;
  position: absolute;
  top:0;
  right: 0;
}
<div >
      <div ></div>
</div>

CodePudding user response:

Spontaneously, I can think of two possibilities. 1) Work with 'position' or 2) work with 'margin'.

here an example with margin in combination flexbox;

.w {
  background-color: lightgray;
  display: flex;
  justify-content: center;
  padding: 20px;
}

.a, .b {
  width: 150px;
  height: 150px;
}

.a {
  background-color: lightblue;
}

.b {
  background-color: lightgreen;
  margin-top: 20px;
  margin-left: -20px;
}
<div >
  <div >A</div>
  <div >B</div>
</div>

  • Related