Dev 404
Dev 404

Reputation: 1587

How to vertically align images inside a list

vertical-align has always given me problems in the past and once again I'm met with a problem that I don't know how to solve.

I have this html:

<ul id="council-slider">
  <li class="col-md-12" style="display: block">
    <img src="somesource" />
    <div class="council-spacer"></div>
    <p>text content goes here</p>
  </li>
</ul>

CSS:

#council-slider {
    margin: 0 auto;
    list-style: none;
    min-height: 300px;
    max-height: 400px;
}

#council-slider li img {
    float: left;
    height: auto;
    width: 25%;
    margin: 5px;
}

.council-spacer {
    height: 300px;
    width: 100px;
    float: left;
}

#council-slider li p {
    margin-top: 100px;
}

I want to be able to vertically align the image in the middle. The text is multiple lines that wrapped so using line-height will not work in this situation. Also the images can have varying heights.

There are multiple list items; I just used one in the example to simplify and reduce the html.

Upvotes: 1

Views: 2096

Answers (4)

Adjit
Adjit

Reputation: 10305

You should read up on where the vertical-align property has the ability to be applied.

Quoting from MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align

The vertical-align CSS property specifies the vertical alignment of an inline or table-cell box.

Since your element is not being displayed as either inline or table-cell vertical-align: middle; will not do you any good here.

You can, however, set your <div> styling to display: table-cell; and then vertical-align: middle

Alternatively, this can be achieved with CSS3 as hars pointed out, just make sure your user's browsers support CSS3

.valign-middle {
   position: relative;
   top: 50%;
   Transform: translateY (-50%);
}

The way this works -

  • Set position relative to the parent/container (i.e. <li> in your case)
  • Move the image that you want to vertically align, down 50% of the container height
  • Move the image up 50% of the height of the image

Upvotes: 2

Sergio Marron
Sergio Marron

Reputation: 521

Will be easier using flexbox: display: flex; and align-items: center;

Demo

#council-slider {
list-style: none;
}

#council-slider li{
    display: flex;
    margin: 10px 0;
    align-items: center;
}
.council-spacer {
    width: 20px;
}

Upvotes: 0

harshitpthk
harshitpthk

Reputation: 4136

Add a class to your img as below.

.verticallyCenter {
  position: relative;
  top:50%;
  Transform:translateY (-50%);}

Refer This

Upvotes: 1

kojow7
kojow7

Reputation: 11384

Without seeing your actual css code it is hard to say, but you should use vertical-align: middle for all objects that you want to align and you may need to change the display of your paragraph to display: table-cell.

Upvotes: 0

Related Questions