Mtok
Mtok

Reputation: 1630

How to horizontally align an img to the center inside the list items

Here is my page structure;

enter image description here

I have images inside all "li" below. I am trying to align these images inside the li elements. I am trying to do this with setting right and left margin to auto but it is not working.

Here is the css;

#navcontainer ul li
{
    display: inline-block;
    width:80px;
}

#navcontainer ul li img
{
    margin-right:auto;
    margin-left:auto;
}

I am sure it is not about accessing the element from css, bcs when I set the width or height or any other thing in the css it is working. But I didnt manage to align it to the center.

Upvotes: 0

Views: 148

Answers (1)

David Thomas
David Thomas

Reputation: 253506

If they're inline-block, simply use text-align: center on the parent li elements.

If they're display: block, then you can use margin: 0 auto 0 auto (top,right,bottom left).

It's also worth pointing out that the only valid children of a ul or ol are li elements. Any other content must be wrapped in an li, otherwise the mark-up is invalid, and then the user-agent tries to correct the mark-up when preparing the DOM. And not consistently across the various user-agents.

Using the following mark-up as a demonstration:

<ul>
    <li class="inlineBlock"><img src="http://lorempixel.com/100/100/sports" /></li>
    <li class="block"><img src="http://lorempixel.com/100/100/nature" /></li>
</ul>​

With the following CSS:

li.inlineBlock {
    text-align: center;
}
li.inlineBlock img {
    display: inline-block;
}

li.block img {
    display: block;
    margin: 0 auto 0 auto;
}​

JS Fiddle demo.

Upvotes: 2

Related Questions