How can I get my divs aligned down the middle?

Viewed 40

I would like to have the player and computer tags vertically aligned down the middle with one another but when I make the position absolute and try to move them, they end up being off kilter with one another. I noticed that when I have both at top: 50% and left: 50% they're positioned how I'd like them to be but when I move them they lose their middle-vertical positioning.

This is how it looks now

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Roboto", sans-serif;
}

body {
  background: #11151c;
}

.comp-name,
.player-name {
  color: white;
  font-size: 24px;
  text-align: center;
  border: crimson 3px solid;
}

.comp-name {
  position: absolute;
  top: 2%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.player-name {
  position: absolute;
  top: 98%;
  left: 50%;
  transform: translate(-50%, -50%);
}

2 Answers

if you set their width equal to each other, then margin-left: auto, margin-right: auto - that should center them. Or you can set display: flex, flex-direction: column, align-items: center on the parent element of the divs you want centered.

absolute layer need a relative wrapper.

<section class="wrapper">
  <span class="comp-name"></span>
  <span class="player-name"></span>
</section>
.wrapper {
  position: relative;
  width: 800px;
  height: 600px;
}

.comp-name,
.player-name {
  position: absolute;
  left: 50%;
  z-index: 9;
  transform: translateX(-50%);
}

.comp-name {
  top: 2%;
}

.player-name {
  bottom: 2%; // recommended fixed pixels: 20px
}
Related