I want to center a div horizontally and vertically at all times.
I can reduce/increase the width of the window and the div will respond by always remaining in the center of the window
.cent
{
height:50px;
width:50px;
background-color:black;
margin:auto;
}
Here is a JSFiddle Example of what I have currently. But I want to keep the div centered vertically as well so if I reduce/increase the height of the window the the div will respond by staying in the middle of the window.
In regards to the example, I want to keep the blackbox vertically centered on window resize in the same way it always stays in the center horizontally.
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
Use a container element and set a specific max-width . A common width many websites use is 960px. To actually center the page, add margin: auto .
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.
Vertically centering div items inside another div Just set the container to display:table and then the inner items to display:table-cell . Set a height on the container, and then set vertical-align:middle on the inner items.
You can do this with CSS tables:
JsFiddle
<div class="container">
<div class="cent"></div>
</div>
html,body
{
height: 100%;
}
body
{
display: table;
margin: 0 auto;
}
.container
{
height: 100%;
display: table-cell;
vertical-align: middle;
}
.cent
{
height: 50px;
width: 50px;
background-color: black;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With