Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/CSS Content always centered

Tags:

html

css

How do I center my page content so it is centered on every type of screen size? For instance, on Allegorithmic if I resize my browser, the center content will shift to the left until it reaches the browser window. There are certain background elements that extend horizontally infinitely (the dark gray at the top, the light grey in the middle, etc.). I can open this website on my laptop and on my iMac and it is centered. I thought I might use absolute positioning to move content x amount of pixels from the left, but that won't work because 300 pixels that center the content on a small screen, won't center it on a large screen.

So in essence I would like to duplicate the functionality of the Allegorithmic website, have backgrounds that are infinite horizontally, but have certain content that always stays "centered".

like image 385
spentak Avatar asked Aug 27 '11 20:08

spentak


1 Answers

If you want elements always centered use margin: 0 auto; in the styles on it.

#yourElement{
    margin: 0 auto;
} 

W3.org reference for centering things using CSS

To get background elements to extend the whole page length just give them a width of 100%, then make a child container within and give them the same style as above. I bet the example you gave is just using a 1px by some height with lines to get that look on the background.

Example

Example with image bg

Markup

<div id="background">
    <div id="content">
    </div>
</div>

CSS

#background{ 
    width: 100%;
}
#content{  
    width: 960px;
    margin: 0 auto;
}
like image 179
Loktar Avatar answered Oct 07 '22 12:10

Loktar