Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering HTML Elements in the Middle of the Page

Tags:

html

css

center

I want to put an HTML element in the middle of the page, horizontally and vertically, but I'm having a hard time making it align even horizontally. I want to center the div "content". Here is my css:

#background
{
position:absolute; 
width:100%; 
height:100%; 
margin:0px; 
padding:0px; 
left:0px; 
right:0px;
z-index:1;
text-align: center;
}

#content
{
margin-left: auto;
margin-right: auto;
 width: 200px;
 z-index: 2;
 position: absolute;
}

And here is my HTML:

<html>
<head>
<link REL="STYLESHEET" TYPE="text/css" HREF="style/myStyle.css"> 
</head>
<body style="padding:0px; margin:0px; overflow:hidden;"> 


 <div id="background"><img src="images/backgroundimage.png" width="100%" height="100%">

 </div>

 <div id="content">

 <p>Here is some content</p>
 </div>

</body>
</html>

Since the div has to be positioned as absolute, doing this:

 margin: 0 auto;

Won't work. I'm not sure what to do. Also, I want it in the center of the page vertically. Help is appreciated, thanks.

Edit: I need the background to be in a separate div so that it's re-sizable, and the content doesn't show if the position is relative.

like image 766
Jack Davis Avatar asked Apr 15 '12 20:04

Jack Davis


People also ask

How do you center in the middle of the page in HTML?

Using the <center></center> tags One way to center text or put it in the middle of the page is to enclose it within <center></center> tags. Inserting this text within HTML code would yield the following result: Center this text!

How do you center all elements in HTML?

This tag has been deprecated in HTML 4 (and XHTML 1) in favor of the CSS text-align property, which can be applied to the <div> element or to an individual <p> . For centering blocks, use other CSS properties like margin-left and margin-right and set them to auto (or set margin to 0 auto ).

How do I center align data in HTML?

To center align text in table cells, use the CSS property text-align. The <table> tag align attribute was used before, but HTML5 deprecated the attribute. Do not use it. So, use CSS to align text in table cells.


1 Answers

<html>
<body> 
 <div id="background">
 <div id="content">
  <p>Here is some content</p>
 </div>     
</div>
</body>
</html>

A better structure for put contents on the middle,without use JQuery:

#background{
background: url(images/backgroundimage.png) top no-repeat;
width:100%;
height:100%;
position:relative;
}

#content{
position:absolute;
top:50%;
left:50%;
width :200px;
height:200px;
margin-left:-100px;
margin-top:-100px;
}
like image 64
José Victor Catalani Avatar answered Sep 30 '22 05:09

José Victor Catalani