Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the body (or div) of fixed size stay always in the center of the page (even vertically!)

Tags:

html

css

I'm trying to make a 1024x768 body to stay always in the center of the page (top-bottom with same spacing, left-right too) however I'm having troubles in doing it.

I used the trick of spacing from top by 50%, then I positioned (absolutely) the body at -384px, which is half of 768.

However this method gives me a problem: if your window is smaller than 768px, you get a scrollbar but a part of the upperside of the body get cut, without any possibility to scroll up (I can still scroll down).

How to solve it?

Edit 1: Here is some code:

  • JS.Fiddle (fullscreen): http://jsfiddle.net/FireDragonDoL/TGjN8/6/embedded/result/
  • JS.Fiddle (normal): http://jsfiddle.net/FireDragonDoL/TGjN8/6/

Html code that can be printed on a simple html web page:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<style>
/**
 *     Change the basic background color of the page
 */
html
{
    background-color: blue;
}

/**
 *     Set the body as a 1024 x 768 rectangle in center of the screen
 */
body
{
    background-color:                   red;
    font-family:      TradeGothic, sans-serif;
    margin-left:                       -512px;
    margin-top:                        -384px;
    position:                        absolute;
    height:                             768px;
    width:                             1024px;
    left:                                 50%;
    top:                                  50%;
}
</style>
</head>
<body>
some text
</body>
</html>
like image 865
Francesco Belladonna Avatar asked Feb 03 '12 02:02

Francesco Belladonna


People also ask

How do you center a fixed div?

If you need to center the fixed element both horizontally and vertically, set the top, left, and transform properties as follows: top: 50%; left: 50%; transform: translate(-50%, -50%);

How do I make a div stay the same size?

if you set width:500px; and height:300px; (or whatever size you want) the div should stay the same size. Also, you can set overflow:hidden; so that if whatever is in the div goes beyond those bounds, it is not shown, and does not resize the div.

How do I fix body size in HTML?

If you set the width to 100% on the body element you will have a full page width. This is essentially equivalent to not setting a width value and allowing the default. If you want to use the body element as a smaller container and let the HTML element fill the page, you could set a max-width value on the body.


1 Answers

Add this:

html {
    position: relative;
    min-width: 1024px;
    min-height: 768px;
    height: 100%;
}

http://jsfiddle.net/thirtydot/TGjN8/9/ (fullscreen: http://jsfiddle.net/thirtydot/TGjN8/9/show/ )

like image 83
thirtydot Avatar answered Oct 27 '22 13:10

thirtydot