How is it possible to create a true center CSS div cross browser for example to use within a holding page?
I have tried this 2007 css trick - How To Center an Object Exactly In The Center but as you can see from my JSFiddle of the code its not 100% center.
HTML:
<div class="center">
<p>Text</p>
</div>
CSS:
.center{
position: fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
border:5px solid black;
}
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.
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.
Simply put, if you have a div, and the elements inside are set to “display:inline-block” then you can just use “text-align:center” to center them inside.
For this to work, you need to have a parent container with the display: table; property, and inside that container you will have the number of columns you want to have centered, with the display: table-cell; (and vertical-align: middle; ) property.
That technique requires the element to have a fixed width and height. You are not setting the width and height. Based on your border and margins, to center it, the width would need to be 190 pixels and the height would need to be 90 pixels. Using line-height
and text-align
in combination with a fixed width and height makes the text and border centered. Try it.
CSS
.center{
position: fixed;
top: 50%;
left: 50%;
width: 190px;
height: 90px;
line-height: 90px;
text-align: center;
margin-top: -50px;
margin-left: -100px;
border:5px solid 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