bjskistad bjskistad - 2 months ago 12
jQuery Question

Centered elements in div appear to be off center

I'm making a website, which for testing reasons I have called

yeet.io
.

I'm currently trying to center an
input
and
h1
inside of a
div
both vertically and horizontally, but for some reason, the elements always appear offsetted somehow.

Why is this? I want the elements to be centered in the middle like any regular "io game". I have some jQuery that makes the elements fade in, could this be the problem? I am stumped.



$(".yeet").hide();
$(document).ready(function() {
$(".yeet").show(2000);
$(".nickname").show(2000);
});

body {
width: 100%;
height: 100%;
}

.container {
text-align: center;
position: absolute;
height: 100%;
width: 100%;
display: table;
}

.yeet {
font-family: "Schoolbell", cursive;
font-size: 75px;
display: table-cell;
vertical-align: middle;
text-align: center;
}

.nickname {
font-family: "Schoolbell", cursive;
display: block;
margin: 0 auto;
text-align: center;
}

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Schoolbell" rel="stylesheet">
</head>

<body>
<div class="container">
<h1 class="yeet">yeet.io</h1>
<input class="nickname" placeholder="nickname" , autofocus="autofocus">
</div>
</body>




Answer Source

You're currently making use of a table, by setting display: table on .container, and display: table-cell on .yeet.

This is probably unintentional, and in fact, simply removing these two declarations automatically produces your desired result -- you don't have to change the HTML at all, or create any new CSS rules.

$(".yeet").hide();
$(document).ready(function() {
  $(".yeet").show(2000);
  $(".nickname").show(2000);
});
body {
  width: 100%;
  height: 100%;
}

.container {
  text-align: center;
  position: absolute;
  height: 100%;
  width: 100%;
}

.yeet {
  font-family: "Schoolbell", cursive;
  font-size: 75px;
  vertical-align: middle;
  text-align: center;
}

.nickname {
  font-family: "Schoolbell", cursive;
  display: block;
  margin: 0 auto;
  text-align: center;
}
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link href="https://fonts.googleapis.com/css?family=Schoolbell" rel="stylesheet">
</head>

<body>
  <div class="container">
    <h1 class="yeet">yeet.io</h1>
    <input class="nickname" placeholder="nickname" , autofocus="autofocus">
  </div>
</body>

Hope this helps! :)