Sam Gentile
Sam Gentile

Reputation: 1349

ASP.NET + CSS - How do I center elements in middle of the web page vertically and horizontally?

My web form is pretty simple. It has to have three lines of text/ASP.NET elements. The Master page has a header and a footer. I need to center those three lines in the middle of the page vertically and horizontally, especially if the bottom changes. How do I do this with CSS?

Upvotes: 2

Views: 13316

Answers (3)

Cybernetic
Cybernetic

Reputation: 13334

This is what worked for me:

<style type="text/css">
  .auto-style1 {text-align:center;}
</style>

Upvotes: 0

Schenz
Schenz

Reputation: 1113

In your master page you will want a container and center that, then you will want a div for the main content. the raw code would be something like:

<div id="center">
   <div id="main">
      <p>This text is perfectly vertically and horizontally centered.</p>
   </div><!-- end #main -->
</div><!-- end #center -->

<style>
   #center { position: absolute; top: 50%; width: 100%; height: 1px; overflow: visible }
   #main { position: absolute; left: 50%; width: 720px; margin-left: -360px; height: 540px; top: -270px } 
</style>

This is using the same approach as offered by Damien. It tends to be the only way to accomplish with CSS alone. You can probably better solve this with the use of JavaScript/jQuery.

Upvotes: 3

Damien
Damien

Reputation: 1217

Horizontally aligning things is simple. If the element has a fixed with give it the following css:

.element
{
      margin: 0 auto;
}

This tells the element to have 0 top and bottom marin and auto-calculate the margin to the left and right.

There is a way to vertically center elements called dead center. It uses a 50% off-set from the top of the page and a negative margin to bring the content to the center (vertically). Drawback is that your element needs have a fixed size (height and width).

Upvotes: 2

Related Questions