Absolute Centering a DIV with CSS Only
Use this snippet to position a div at the absolute center of your browser window, both horizontally and vertically. Replace the is-Fixed class with is-Responsive for responsive web design. The snippet was originally shared on CodePen.
<div class="Center-Container">
<div class="Absolute-Center is-Fixed"></div>
</div>
<style>
/*
////////////////////////////////////////
Absolute Centering
////////////////////////////////////////
*/
.Absolute-Center {
height: 50%; /* Set your own height: percents, ems, whatever! */
width: 50%; /* Set your own width: percents, ems, whatever! */
overflow: auto; /* Recommended in case content is larger than the container */
margin: auto; /* Center the item vertically & horizontally */
position: absolute; /* Break it out of the regular flow */
top: 0;
left: 0;
bottom: 0;
right: 0; /* Set the bounds in which to center it, relative to its parent/container */
background-color: #000;
}
/* //////////////////////////////////////// */
/* Make sure our center blocks stay in their container! */
.Center-Container {
position: relative;
}
/* //////////////////////////////////////// */
/* Fixed floating element within viewport */
.Absolute-Center.is-Fixed {
position: fixed;
z-index: 999;
}
/* //////////////////////////////////////// */
/* Min/Max Width */
.Absolute-Center.is-Responsive {
width: 60%;
height: 60%;
min-width: 200px;
max-width: 400px;
padding: 40px;
}
</style>
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory