daveycroqet
daveycroqet

Reputation: 2727

Center an element in a fixed position on a resizable background

I'm trying to center an element of a precise size on a background that is built specifically for it, in order to make it appear seamless.

In the following code, #window represents the browser's window size in pixels (change it to anything). #background obviously refers to the background image I'll be using, and #positionMe is the object I want to fit on the background. I want the background to always be centered in the browser even if the window is resized, and I want the kitten to always be centered in the black box on the background.

As you can see below, the problem is that the background isn't centered on the viewport to begin with; it's centered based on total width of the browser. And when you resize the screen, it doesn't adjust accordingly.

HTML:

<div id="window">
    <div id="background">
        <img id="positionMe" src="http://cs421018.vk.me/v421018778/74bc/NearuIJQIck.jpg" />
    </div>
</div>

CSS:

#window {
    background-color: red;
    width: 1280px;
    height: 720px;
}
#background {
    background: url('http://i.imgur.com/xzDclz5.jpg') no-repeat;
    width: 500px;
    height: 500px;
    margin: 0 auto;
}
#positionMe {
    position: relative;
    top: 174px;
    left: 154px;
}

This Fiddle demonstrates my issue.

Upvotes: 1

Views: 1588

Answers (2)

smts
smts

Reputation: 3825

Using a combination of display:table-cell and vertical-align:center will center your image vertically. In addition, you can simply use text-align:center to center your image horizontally.

http://jsfiddle.net/reinmcha/XtQ37/10/

Might need to do a little adjusting to keep the background div centered. So, we add another div and set to display:table. The "table cell" will fill the whole thing. Now we center the table with margin: 0 auto.

Final Product:

http://jsfiddle.net/reinmcha/XtQ37/20/

Might need to do some updating to get the image to center perfectly with the border (since it has width...)

Here's my go at it.

I hope you are aware there are tons of articles on this topic. Search around. You'll find your answer :)

Upvotes: 2

Kęstutis
Kęstutis

Reputation: 1061

You basically have two options, one would be using a div to display an image and making the image a centered background like so:

<div id="window">
    <div id="background">
        <div id="centerMe"></div>
    </div>
</div>

with css:

#centerMe {
width: 100%;
height: 100%;
background: url('http://cs421018.vk.me/v421018778/74bc/NearuIJQIck.jpg') no-repeat center;
}

or for a pure css solution:

#background {
    background: url('http://i.imgur.com/xzDclz5.jpg') no-repeat;
    width: 500px;
    height: 500px;
    margin: 0 auto;
    text-align: center;
}
#background:before {
    content: "";
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
#centerMe {
    vertical-align: middle;
}

Upvotes: 1

Related Questions