What would be the correct method to vertically center any content in a defined width/height div
.
In the example there are two contents with different heights, what is the best way to center vertically both using the class .content
. (and it works for every browser and without the solution of table-cell
)
Have some solutions on mind, but would like to know other ideas, one is using position:absolute; top:0; bottom: 0;
and margin auto
.
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.
The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.
To get them centered along a line, you'd use vertical-align: middle; . Although note that it centers the text according to its tallest ascender and deepest descender. Each element lines up according to the line you've set, which doesn't change from element to element.
I have researched this a little and from what I have found you have four options:
If you do not mind using the display:table-cell
on your parent div, you can use of the following options:
.area{ height: 100px; width: 100px; background: red; margin:10px; text-align: center; display:table-cell; vertical-align:middle; }
Live DEMO
.area{ height: 100px; width: 100px; background: red; margin:10px; text-align: center; display:block; } .content { height: 100px; width: 100px; display:table-cell; vertical-align:middle; }
Live DEMO
.area{ background: red; margin:10px; text-align: center; display:block; float: left; } .content { display:table-cell; vertical-align:middle; height: 100px; width: 100px; }
Live DEMO
The only problem that I have had with this version is that it seems you will have to create the css for every specific implementation. The reason for this is the content div needs to have the set height that your text will fill and the margin-top will be figured off of that. This issue can be seen in the demo. You can get it to work for every scenario manually by changing the height % of your content div and multiplying it by -.5 to get your margin-top value.
.area{ position:relative; display:block; height:100px; width:100px; border:1px solid black; background:red; margin:10px; } .content { position:absolute; top:50%; height:50%; width:100px; margin-top:-25%; text-align:center; }
Live DEMO
This could also be done using display: flex
with only a few lines of code. Here is an example:
.container { width: 100px; height: 100px; display: flex; align-items: center; }
Live Demo
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