Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

True Center Vertical and Horizontal CSS Div [duplicate]

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;
}
like image 804
Jess McKenzie Avatar asked Jan 07 '13 03:01

Jess McKenzie


People also ask

How do I center a div vertically and horizontally in CSS?

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 center a div in CSS 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.

How do I center 2 divs?

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.

How do you vertically align a div in CSS?

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.


1 Answers

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;
}
like image 168
icktoofay Avatar answered Oct 14 '22 19:10

icktoofay