Dirty Penguin
Dirty Penguin

Reputation: 4402

How to fit content inside a background-image

How would one ensure that certain content is always fitted inside a particular area of a web page?

As an example, I would like the sentence "Fit this inside" to appear inside of the background image. Here is my test.html file:

<!DOCTYPE html>
<html lang="en">
    <link href="test.css" rel="stylesheet" type="text/css">
    <body>Fit this inside</body>
</html>

Here is my test.css file:

body
{
    background-image: url('bg_img.png');
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: fixed;
    background-size:100% 68%;
    overflow: scroll;
}

This results in the text "Fit this inside" appearing at the very top of the page, and not inside the background image area.

What is the correct method to do this?

JSFiddle: http://jsfiddle.net/u3TAF/

Upvotes: 1

Views: 2542

Answers (3)

KM123
KM123

Reputation: 1377

I think the best option would be to put the text within a DIV and then apply the styles to that element. Somewhere along the lines of:

<html>
<head>
<style type="text/css">
#test{
    background-image: url('bg_img.png');
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: fixed;
    background-size:100% 68%;
    overflow: scroll;
    }   
</style>
</head>
<body>
<div id="test">
Fit This Inside
</div>
</body>
</html>

Upvotes: 2

Guy Dafny
Guy Dafny

Reputation: 1829

Look at my comment higher. You've set the background image to be 68% height. set the text into container with same properties.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title> Bla! </title>
        <style type='text/css'>
            body
            {
                background-image: url('image.png');
                background-repeat: no-repeat;
                background-position: center center;
                background-attachment: fixed;
                background-size:100% 68%;
            }
            div.container {
                position:absolute;
                top:16%;
                height: 68%;
                left: 0%;
                overflow:auto;
            }        
        </style>
    </head>
    <body>
        <div class='container'>
            Now it's fit!
        </div>
    </body>
</html>

Upvotes: 2

sanjeev mk
sanjeev mk

Reputation: 4336

The background image should be given to the parent element. In your case, in the CSS, attach the background image property to the <html> element. So this image would act as a background to all the content of this page.

If that is what your aim is, then:

    html{
         background: url('bg_img.png') no-repeat center center fixed;
    }

Upvotes: 0

Related Questions