byronyasgur
byronyasgur

Reputation: 4747

Centre image horizontally inside li where image wider than li

What options (if any) do I have to centre the image within the li tag? What I have is an oversized image deliberately placed into a smaller sized li. What I am trying to achieve is the image centred within the li tag ... ie so that the cropped overflow would be shared on both the left and right, not just the right. The code below is a reduced version of what I am working with.

HTML

<ul>
  <li>
    <img src = "http://placehold.it/400x100">
  </li>
</ul>

CSS

li{
  overflow:hidden;
  width: 250px;
}
img {
  border: 3px solid pink;
}

The codepen is here http://codepen.io/anon/pen/ebCEi. Note: I wont be able to use background images.

Upvotes: 1

Views: 74

Answers (3)

j08691
j08691

Reputation: 208040

li {
    overflow:hidden;
    width: 250px;
    position:relative;
    height:106px;
}
img {
    border: 3px solid pink;
    position:absolute;
    left:-75px;
}

jsFiddle example

You'll notice the left and right border on the image isn't visible because it extends beyond the viewport of the list item.

Upvotes: 2

Bhushan Firake
Bhushan Firake

Reputation: 9468

Try this:

HTML

<ul>
  <li>
    <img src = "http://placehold.it/400x100">
  </li>
</ul>

CSS

li{
  overflow:hidden;
  text-align:center;
  width: 250px;
}
img {
  border: 3px solid pink;
  margin:0 auto;
}

Upvotes: 0

Kevin Boucher
Kevin Boucher

Reputation: 16705

Use text-align:

li {
   overflow:hidden;
   text-align: center; /* <-------  */
   width: 250px;
}

If that doesn't work try this:

img {
    border: 3px solid pink;
    margin: 0 auto; /* <-------  */
}

Upvotes: 0

Related Questions