user3692451
user3692451

Reputation: 569

CSS - How can I vertically align a div without using "position: absolute"?

How can I vertically align a div without using position: absolute?

I created the fiddle: https://jsfiddle.net/h5c21hmj/14/

#main {
    margin: auto;
    width: 300px;
    height: 200px;        
}

.image {
    background-image: url(http://www.todopuertas.net/images/conoce.png);
    height: 100px;
    right: 0;
    bottom: 0;
    background-size: contain;
    background-repeat: no-repeat;

}

.column1 {
    float: left;
    width: 100px;
    height: 100px;
    position: relative;
    vertical-align: bottom;
}

.column2 {
    float: right;
    right: 0;
    width: 150px;
    position: relative;
    height: 140px;
    background-color: #FFFF00;
}
<div id="main">
    <div class="column1">
        <div class="image"></div>
    </div>
    <div class="column2">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sit amet egestas urna. Sed dignissim bibendum ante, sit amet accumsan erat ornare quis. Proin in neque diam. Phasellus rhoncus hendrerit leo, sit amet feugiat ante pellentesque vitae.
    </div>
</div>

What I want to do is to get the div that contains the image and align it to the bottom, but I need to achieve that without using "absolute" positioning, only using "relative" positioning on all elements.

I can't use "absolute" because it gets above other elements.

Upvotes: 0

Views: 532

Answers (2)

Yandy_Viera
Yandy_Viera

Reputation: 4380

You can use flexbox like this:

Here a working JSFiddle fork from yours

#main {
    margin: auto;
    width: 300px;
    display: flex; /*added*/
}

.image {
    background-image: url(http://www.todopuertas.net/images/conoce.png);
    height: 100px;
    right: 0;
    bottom: 0;
    background-size: contain;
    background-repeat: no-repeat;
    background-position-y: 100%;  /*added to bottom align the img*/
}

.column1 {
    float: left;
    width: 100px;
    position: relative;
    align-self: flex-end; /*added to aligned to bottom*/
    border: 1px solid; /*to show that is aligned*/
}

.column2 {
    float: right;
    right: 0;
    width: 150px;
    position: relative;
    background-color: #FFFF00;
}
<div id="main">
    <div class="column1">
        <div class="image"></div>
    </div>
    <div class="column2">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sit amet egestas urna. Sed dignissim bibendum ante, sit amet accumsan erat ornare quis. Proin in neque diam. Phasellus rhoncus hendrerit leo, sit amet feugiat ante pellentesque vitae.
    </div>
</div>

Upvotes: 1

Shan Robertson
Shan Robertson

Reputation: 2742

Check out my updated fiddle. Basically, i removed the floats and set your elements to align bottom, by setting them as inline-block elements.

Upvotes: 0

Related Questions