Ana Ameer Ana Ameer - 1 month ago 10
CSS Question

CSS - How to make a div's padding not affect the positioning of the div below it

So I have two boxes:
https://jsfiddle.net/anaegm/trajtmgf/

My original intention was to make

box-1
expand its height from the top and bottom when you hovered over it (as opposed to just "growing down" by adding padding), so I added a negative margin-top under the :hover to achieve this effect, and it works.

The problem is that
box-2
below gets pushed down when you hover over
box-1
, and I need the second box to stay in its original position at all times. I tried adding a margin at the top of
box-2
, but this doesn't work. What are my options?

EDIT: Since I'm working with dynamic text for the actual page I'm doing, I'd rather not use a set height for a div container for
box-1
.



#box-1 {
color: #fff;
background-color: #e91d23;
text-align: center;
cursor: pointer;
width: 100px;
padding-top: 30px;
padding-bottom: 30px;
}
#box-1:hover {
background-color: #5A5A5A;
margin-top: -10px;
padding-top: 40px;
padding-bottom: 40px;
}
#box-2 {
width: 100px;
background-color: white;
text-align: center;
padding-top: 30px;
padding-bottom: 30px;
margin-top: 50px;
}

<div id="box-1">
Box 1
</div>
<div id="box-2">
Box 2
</div>




Answer

Use absolute positioning.

#box-1 {
  position: absolute;
  color: #fff;
  background-color: #e91d23;
  text-align: center;
  cursor: pointer;
  width: 100px;
  padding-top: 30px;
  padding-bottom: 30px;
}
#box-1:hover {
  background-color: #5A5A5A;
  margin-top: -10px;
  padding-top: 40px;
  padding-bottom: 40px;
}
#box-2 {
  position: absolute;
  width: 100px;
  background-color: white;
  text-align: center;
  padding-top: 30px;
  padding-bottom: 30px;
  top: 100px;
}
<div id="box-1">
  Box 1
</div>
<div id="box-2">
  Box 2
</div>

I hope this was what you were trying achieve.

Comments