Jakob Nielsen
Jakob Nielsen

Reputation: 5198

how to center image + text in an li Element

basicly I have li elements which contain a small icon an a text, i want to horizontally and vertically center those elements together. However i dont get it working, since Im not really experienced in CSS.

I already managed to vertically center the elements using two spans and line-height. But Im failing with the horizontal centering, since text align doesnt work for spans, and float middle doesnt exist.

You guys have some ideas??

here my code:

HTML:

echo "<li style=\"background-color:#f7f7f7; color:#2EA620;\"><span class=\"image\"><img src=\"Images/List/Teams/" . $temp . ".png\" /></span><span class=\"text\">".$obj_teams->Name."</span></li>";

CSS:

li {
    width:173px;
    height:30px;
    line-height:30px;
    font:"Myriad Pro";
    font-size:14px;
    padding-left:10px;
    padding-right:10px;
    border-bottom:1px solid;
    border-left:1px solid;
    border-right:1px solid;
    border-color:#CCC;
}

.image {
    float:left;
    text
}

.text {
    float:left;
    color:#2EA620;
    line-height:30px;
}

Here an Image of how it looks like now. (If marked the elements which i want to center)

http://i.imgur.com/tI9Vulf.png

Upvotes: 0

Views: 6296

Answers (3)

user1934286
user1934286

Reputation: 1762

Your specific problem is that you are floating the image and span left but then want them centered. Remove the float left on both then you can put text-align: center on your li elements.

li {
width:173px;
height:30px;
line-height:30px;
font:"Myriad Pro";
font-size:14px;
padding-left:10px;
padding-right:10px;
border-bottom:1px solid;
border-left:1px solid;
border-right:1px solid;
border-color:#CCC;
text-align:center;
}

.text {
color:#2EA620;
line-height:30px;
}

Upvotes: 1

ajp15243
ajp15243

Reputation: 7952

Try applying text-align: center; to the parent (or any ancestor) element of your span since a span is an inline element (assuming .text is your span).

Or try making the span a block element and setting its left and right margins to auto:

.text {
    display: block;
    margin: 0 auto;
}

Inline elements like spans respond to text-align on their ancestor elements, whereas block elements like divs respond to setting margins to auto. Note that text contained inside of an element will respond to text-align that is placed on that element (since the text is technically a "text node" inside of that element).

Upvotes: 1

Ismael Ghalimi
Ismael Ghalimi

Reputation: 3565

You could use a text-align rule:

li.center {
  text-align: center;
}

Take a look at this fiddle for a live example:

http://jsfiddle.net/fX9jp/1/

Upvotes: 3

Related Questions