Search code examples
htmlcssbuttoncenter

I cannot center my button and don't know why


I tried to put a button in the center of my div but I couldn't though all my other contents are centered.

My code:

.middle {
  width: 100%;
  height: auto;
  text-align: center;
  position: relative;
}

.middle section {
  padding: 18vh 6%;
  line-height: 0.5;
  color: #EE6352;
  font-weight: 400;
  font-size: calc(16px + 3vw);
}

.middle ul {
  text-align: left;
}

.middle li {
  font-size: calc(12px + 2vw);
  line-height: 1.25;
  color: #2A2D34;
}

.middle p {
  font-size: calc(14px + 2.4vw);
  font-weight: 400;
  color: #2A2D34;
}

.upbutton {
  padding: 10px;
  background: #1ac6ff;
  border-radius: 50%;
  border-style: none;
  cursor: pointer;
  position: absolute;
  top: 0px;
  transition: background 0.3s;
  box-shadow: 2px 2px 5px rgba(102, 102, 102, 0.5);
}

.upbutton img {
  width: 25px;
  height: 25px;
}

.upbutton:hover {
  background: #00ace6;
  -webkit-transform: scale(0.94);
  -ms-transform: scale(0.94);
  transform: scale(0.94);
}

.upbutton:active {
  background: #0086b3;
}
<a id="middle">
  <div class="middle">
</a>
<section>
  <a href="#top"><button class="upbutton"><img src="img/arrow.png"></button></a>
  <h1>content</h1>
  <ul>
    <li>content</li>
    <li>content</li>
    <li>content</li>
  </ul>
  <p>...and more</p>
</section>
</div>

I also searched on this problem and tried to put this into the .upbutton class:

margin:0;
-ms-transform: translateX(-50%);
transform: translateX(-50%); 

and it centered my button. But when I hover, it didn't center anymore.

I don't know why I'm kinda new to this. Can anyone explain and help me, tks a lot!


Solution

  • Remember to add a transform: translateX(-50%); on the :hover selector for the button, this way it wont go back. If you change the transform property on hover it overides the existing one, so it goes back to translateX(0)

        .upbutton:hover {
      background: #00ace6;
      -webkit-transform: translateX(-50%) scale(0.94);
      -ms-transform: translateX(-50%) scale(0.94);
      transform: translateX(-50%) scale(0.94);
    }