Forum Moderators: not2easy

Message Too Old, No Replies

Centering an image in an HTML element that is display:block

         

towerofbabel

7:53 pm on Apr 24, 2008 (gmt 0)

10+ Year Member



Hi all,

definitely a classic newbie post:

I am fairly new to CSS, and having just built my first complete website styled with CSS, and learnt my way around a bit, I have a problem I can't seem to solve -

I am using an unordered list for navigation, and each <a> element of the navigation is actually a jpg. With my CSS, when I have text only and not the jpg in the <a> element, it centeres as I desire, but when I have the jpg display, it aligns to the left, seemingly no matter what I try to do to change that behavior.

Here is my CSS for the navigation:


#nav {
height: 60px;
font-size:0.75em;

background: #EAF1F9;

text-align: center;

margin: 0;

padding: 0;
border-style: solid;
border-width: 0 0 1px 0;
border-color: #2B5468;

}

#nav ul {

margin:0;

padding:0;

list-style-type:none;
margin: 0;
padding: 0 0 0 33px;

}

#nav li {

display:inline;
float: left;

margin:0;

padding:0;

}

#nav ul li a {

display: block;

width:121px;

height: 16px;

text-decoration:none;
font-weight: bold;
color: #2b5468;

padding: 0;

margin: 22px 0 0 0;
border-style: solid;
border-width: 0 0 0 1px;
border-color: #2B5468;

}

#nav ul li a:hover {

background-color:#EAF1F9;
color:#831e14;

}

#nav img {
display:block;
margin:0;
padding: 0px;
border-style: none;
}

Here is my doc type:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

I can't work out what I need to do to #nav img in order to make it center correctly with the <a> HTML element.

Can anyone see what I am missing? Thanks.

londrum

8:33 pm on Apr 24, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



there are a few ways of doing it. the easiest-- if the images are all the same size-- would be to give them a specific margin.
so if #nav ul li a is 121px wide, and the image is always 61px, then give it 30px either side.

or you could just give the images
margin:0 auto;
but that will not work on older browsers.

using text-align:centre on #nav li might also work

towerofbabel

11:03 am on Apr 25, 2008 (gmt 0)

10+ Year Member



Thanks for your help londrum. Actually, none of those methods worked, and I had tried them all. But, it got me thinking further, and I realised I was trying to style an image which is not in the HTML at all - I mean, the jpgs are in the css as "background-image" so a simple "background-position: center center;" solved my problem!