How to position a background image for a web page with CSS

When you add a single, not-repeating background image to your Web page, it appears, by default, in the top left corner of the viewpoint. You can set the image to be displayed anywhere else on the page, by using CSS property background-position. The next CSS test file centers the image on the page:

File test.css

body {

background-color: #ffffff;

background-image: url(psy.jpg);

background-repeat: no-repeat;

background-position: center center;

}

h1 {

text-align: center;

font: 24px Arial, Helvetica,Geneva ,Verdana, sans-serif;

}

p {

text-align: center;

font: 14px Arial, Helvetica,Geneva ,Verdana, sans-serif;

line-height: 1;

}

 

You can use for example the next test file:

 

File test.html

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en-US”>

<head>

<title>How to position a background image for a web page with CSS</title>

<meta http-equiv=”content-type” content=”text/html; charset=utf-8″ />

<link rel=”stylesheet” type=”text/css” href=”test.css” />

</head>

<body>

<h1>Oppa is Gangnam style Gangnam style</h1>

<p>A girl who is warm and humanle during the day</p>

<p>A classy girl who know how to enjoy the freedom of a cup of coffee</p>

<p>A girl whose heart gets hotter when night comes</p>

<p>A girl with that kind of twist</p>

<p>I&#39;m a guy</p>

<p>A guy who is as warm as you during the day</p>

<p>A guy who one-shots his coffee before it even cools down</p>

<p>A guy whose heart bursts when night comes</p>

<p>That kind of guy</p>

<p>Beautiful, loveable</p>

<p>Yes you, hey, yes you, hey</p>

<p>Beautiful, loveable</p>

<p>Yes you, hey, yes you, hey</p>

<p>Now let&#39;s go until the end</p>

<p>Oppa is Gangnam style, Gangnam style</p>

<p>Oppa is Gangnam style, Gangnam style</p>

<p>Oppa is Gangnam style</p>

<p>Eh- Sexy Lady, Oppa is Gangnam style</p>

<p>Eh- Sexy Lady oh oh oh oh</p>

</body>

</html>

The next picture shows the result:

Positioning a background image for a web page with CSS

Positioning a background image for a web page with CSS

 

Important notes:

Other values for background-position are:

– top left

– top center

– top right

– center left

– center center

– center right

– bottom left

– bottom center

– bottom right

If you only specify one of the values, the other will default to center.

background-position: top;

The above code is the same as the following:

background-position: top center;