Home > Net >  CSS margin-top moving element down
CSS margin-top moving element down

Time:07-05

I have a context of 3 divs, one parent, and two children. The two children are placed one on top of the other and I want to add a margin-top on the bottom one to move the one on top 50px up. What ends up happening is that the one on the bottom moves down 50px instead.

Here is the code:

.container {
  background-color: red;
  width: 500px;
  height: 300px;
  position: relative;
  margin: auto;
  font-size: 30px;
}

.top,
.bottom {
  height: 100px;
  width: 100px;
}

.top {
  background-color: purple;
}
.bottom {
  margin-top: 50px;
  background-color: blue;
}
<body>
   <div >
       <div >top</div>
       <div >bottom</div>
   </div> 
</body>

Any suggestions?

CodePudding user response:

CSS allows you to move an element relative to its position without affecting other elements' positions if you use transform.

In this case you can translate the top element in the Y direction by -50px to move it up:

.container {
  background-color: red;
  width: 500px;
  height: 300px;
  position: relative;
  margin: auto;
  font-size: 30px;
}

.top,
.bottom {
  height: 100px;
  width: 100px;
}

.top {
  background-color: purple;
  transform: translateY(-50px);
}

.bottom {
  background-color: blue;
}
<body>
  <div >
    <div >top</div>
    <div >bottom</div>
  </div>
</body>

CodePudding user response:

gap (grid-gap) Syntax gap: 50px;

CodePudding user response:

As you can see the first element is already on the highest point inside the parent container. html What you can do is in case you want to increase its height is scaling its y position by a negative number.

  • Related