Home > Net >  CSS button hover and activation moves the paragraph which is below it
CSS button hover and activation moves the paragraph which is below it

Time:06-10

So I have been trying to cause the button to stretch when I hover over it and for it to have a 3D effect when I click on it. All is good on the button's end and it does exactly as it should. Problem is...when the button stretches, the paragraph below it also moves down and the paragraph moves even farther down when I press the button. Anyway this can be rectified so the position of the paragraph remains fixed?

.test-button {
  background-color:navy;
  color:white;
  border:none;
  cursor:pointer;
  padding-top:8px;
  padding-bottom:8px;
  padding-left:15px;
  padding-right:15px;
  font-size:18px;
  box-shadow:3px 3px 5px rgba(0, 0, 0, 0.5);
  transition:padding 0.15s;
}

.test-button:hover {
  padding-bottom:18px;
  padding-top:18px;
  padding-right:25px;
  padding-left:25px;
}

.test-button:active {
  margin-top:3px;
  margin-bottom:3px;
  box-shadow:none;
}

image of the sample code

CodePudding user response:

When you hover, your button is going from 8px top and 8px bottom padding (16px of height padding) to 18px top and 18px bottom (36px of height padding) which will push down the paragraph.

When you click on it, triggering the :active rule, your height padding will remain because you will still be hovering on it but you will also gain the 3px top and 3px bottom of margin area (additional 6px height), pushing the paragraph further down once again.

For the paragraph to not move when the button grows in height like this, you could contain the button in an element of a fixed height such that the paragraph will always sit below this fixed element, as long as the button has sufficient room to grow within it.

CodePudding user response:

Many solutions are possible here:

One of them is you can just take the paragraph element out of the flow of HTML by positioning it as absolute but you have to be careful as it might lead to overlapping.

The Second one would be little tricky and time-consuming, you need to understand the box model for both the button element and paragraph element, then assign the values as such, so that they won't interrupt each other's box model.

The Third one would be just wrapping both of the elements into separate containers and assigning those containers a height such that even after hovering, the boundaries/paddings, margins, etc, of elements remain inside the height of the container. By doing this you would make sure that nothing of shifting sort happens. This involves basic maths and box model study to achieve the same.

I think 3rd option would be best for your case.

  • Related