My code is as follows:
<div id="bigDiv">
<div id="smallDiv">DD</div>
</div>
My CSS is as follows:
#bigDiv {
border: 1px solid red;
height: 300px;
width: 300px;
vertical-align: middle;
}
#smallDiv {
border: 1px solid black;
height: 100px;
width: 100px;
margin: 0 auto;
}
I want to center the small div vertically and horizontally inside the big div. The horizontal works, but the vertical doesn't.
http://jsfiddle.net/4Gjxk/
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.
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. This has broad compatibility back as far as the days of IE9.
To Horizontally centered the <div> element: We can use the property of margin set to auto i.e margin: auto;. The <div> element takes up its specified width and divides equally the remaining space by the left and right margins.
The CSS vertical align property works smoothly with tables, but not with divs or any other elements. When you use it in a div, it aligns the element alongside the other divs and not the content — which is what we usually want). This only works with display: inline-block; .
Read this: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
If you cannot be bothered reading do this:
#bigDiv {
position: relative; /* Needed for position: absolute to be related to this element and not body */
border: 1px solid red;
height: 300px;
width: 300px;
vertical-align: middle;
}
And change the other to:
#smallDiv {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
border: 1px solid black;
height: 100px;
width: 100px;
}
Here is the updated jsfiddle: http://jsfiddle.net/4Gjxk/1/
I believe this is the most straight-forward solution with the least amount of CSS. Since 100 / 300 = ~.33 you can use a 33% margin like so:
#bigDiv {
border: 1px solid red;
height: 300px;
width: 300px;
}
#smallDiv {
border: 1px solid black;
height: 100px;
width: 100px;
margin: 33%;
}
Here's the updated jsFiddle.
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