D SPECIAL
D SPECIAL

Reputation: 21

CSS/HTML - Centering Absolute Positioned Image

I've been at this for quite a while now, and can't seem to get a grip on it. I was wondering how to make my ".logo" class centered?

#wrap {
    width: 960px;
    height: auto;
    min-height: 700px;
    margin: 0 auto;
}

.logo {
    background: url(../images/logo.png);
    width: 269px;
    height: 126px;
    z-index: 1000;
    position: absolute;
}        

<div id="wrap">
    <div class="logo"></div>
    <div id="nav"></div>
</div>

Thanks in advance!

Upvotes: 0

Views: 3970

Answers (5)

Brian
Brian

Reputation: 2829

Since you have a fixed width container hold the absolute element, all you actually need to do is add:

left: 50%;
margin-left: -134px;

to .logo and you're good. The margin-left should be 1/2 of the absolute element's width. This, assuming you are only going for a horizontal center. Vertical would work similar with a top/margin-top, but that would require a fixed height.

Upvotes: 3

srini
srini

Reputation: 884

use margin:0 auto;

This logo is horizontally centered by setting its right and left margin widths to "auto". This is the preferred way to accomplish horizontal centering with CSS

example css

          .logo{
                background: url(../images/logo.png);
                width: 269px;
                height: 126px;
                z-index: 1000;
                margin:0px auto; //or margin:0 auto;
                 } 

                }

Upvotes: 0

user900360
user900360

Reputation:

There are some solutions. A word about absolute though, 'bitch' it is.

http://jsfiddle.net/UY2FC/4/

http://jsfiddle.net/UY2FC/3/

http://jsfiddle.net/UY2FC/1/

each one does the same job, but with subtle differences.

Though, what's with z-index? are you masking something?

Upvotes: 0

Ayyash
Ayyash

Reputation: 4399

just add background-position: center center; and define the background better:

background-image: url() 
background-repeat: no-repeat; 
background-position: center center; // you can have top bottom left right as well

Upvotes: 1

user610217
user610217

Reputation:

I would create a div with the right and left properties the same, put my objects in the div, and either set the margin-right and margin-left properties for the child objects to auto or set the text-align attribute to center. This should center most objects.

BTW, be careful with absolute positioning. It can get ugly.

Upvotes: 0

Related Questions