GCW
GCW

Reputation: 312

How to vertically align images without absolute positioning in a responsive layout

I know that margin-left:auto; and margin-right:auto; make an element to be centered as text-align:center; does.

My question is about the vertical alignment.

I would like to keep my images centered in relation with my vh.

<section> 
  <div class="half">
    <img />
  </div>

  <div class="half">
    <img />
  </div>
</section>

STYLE:

.half {
height:100%;
width: 50%;
display:inline-block;
float:left;  
}

.half img {
max-width:93%;
max-height:90%;
}

An example on Fiddle: http://jsfiddle.net/f16wpgpm/3/

Upvotes: 0

Views: 1779

Answers (3)

BurpmanJunior
BurpmanJunior

Reputation: 1008

You can use the table display method to vertically align responsively. However, this requires an inner <div> to act as the cell to align:

<div class="half first_half">
    <div class="inner">
        <img src="http://www.capitale-creativo.it/img/capcrea1.jpg" />
    </div>
</div>

Then by making .half display as a table and the .inner display as its cell, you can add a vertical-align: middle; like so:

.half{
    height:100%;
    width: 50%;
    display:table;
    float:left;
}

.inner{
    display: table-cell;
    vertical-align: middle;
}

Here it is in action: http://jsfiddle.net/f16wpgpm/4/

Upvotes: 1

Scott Rowell
Scott Rowell

Reputation: 1130

http://jsfiddle.net/f16wpgpm/6/

you can use display:table and display:table-cell for this.

section {
    display:table;
    width:100%;
}

.half {
    width: 50%;
    display:table-cell;
    vertical-align:middle;
}

Upvotes: 1

APAD1
APAD1

Reputation: 13666

Add position:relative; to .half and then add the following CSS to your img selector:

margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;

Updated Fiddle

Upvotes: 3

Related Questions