Shreyas Sreenivasa Shreyas Sreenivasa - 1 month ago 6
CSS Question

How do I make the <div> in the center of the page?

I want the div #container to be in the center of the page. Like horizontally and vertically. I tried to make

position: absolute; top: 50%; bottom: 50%; left: 50%; right: 50%
but it didn't work. And it has to be like in the center of the page no matter the size of the display. Thank you in advance!

Heres my code:



@import url('https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900|Droid+Sans:400,700|Josefin+Sans:100,100i,300,300i,400,400i,600,600i,700,700i|Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i|Oxygen:300,400,700|Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i|Ubuntu:300,300i,400,400i,500,500i,700,700i');
#container {
width: 30em;
background-color: #eee;
height: 30em;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
}
#wrapper {
width: 30rem;
height: 30rem;
border-radius: 50%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<div id="main-head">
<a href="#"><h2 id="main-heading">sKoolBook</h2></a>
</div>
</header>
<section>
<div id="container">
<div id="wrapper">
<script type="text/javascript">
var dataCap = document.getElementById("chooseSchool").value;
document.write(dataCap);
</script>
<form method="POST" id="chooseSchool">

</form>
</div>
</div>
</section>
<footer>
</footer>
<p id="demo"></p>




Answer

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
}
<div class="centered">This div is centered</div>

Note: Transforms are pretty well supported by browsers nowadays, see http://caniuse.com/#search=transform