Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a div horizontally and vertically and keep centered when resizing the parent [duplicate]

Tags:

html

css

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.

like image 515
Aaron Avatar asked Jul 08 '13 06:07

Aaron


People also ask

How do you center align a div both horizontally and vertically?

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.

How do I keep my container in the center?

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 .

How do you center elements vertically and horizontally?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

How do I vertically center a div in another div?

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.


1 Answers

You can do this with CSS tables:

JsFiddle

Markup

<div class="container">
    <div class="cent"></div>
</div>

(Relevant) CSS

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;      
}
like image 97
Danield Avatar answered Oct 07 '22 11:10

Danield