简体   繁体   中英

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.

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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM