简体   繁体   中英

Centert align vertically element when container height is unknown

I have a row of two columns, one column contains an image and the other column some text. Is there a way I can always vertically align the text within the column so that it is always centered vertically? You can see an example here on the fourth and fifth row of what I'm trying to do:

http://machinas.com/wip/hugoboss/responsive-img/

The height depends on the size of the image really so I can't really set a height of the column.

HTML

<div class="row">
    <div class="large-6 column">
        <div class="txt-block">
            <h3>Lorem ipsum dolor</h3>         
            <p>Vivamus eget tempus magna. Proin dignissim, est ac mollis viverra, ligula leo fringilla dolor, in porttitor quam lectus eget augue. Etiam vel felis at mauris pellentesque cursus dignissim in nunc.</p>    
            <div class="center-wrap">
                <div class="center">
                    <a href="link" class="jetzt-entdeck">Jetzt entdecken</a>
                </div>
            </div>   
        </div>
    </div>
    <div class="large-6 column">
        <img src="http://placehold.it/470x400" alt="">
    </div>

CSS

.column {
    display: table;
    float: left;
    height: 100%;
    padding-left: 0.5rem;
    padding-right: 0.5rem;
    position: relative;
}

You need to remove floats on the large-6 column div and add vertical align middle, also you should be displaying those as table-cells not tables. The row is acting as a table. See css below;

.large-6.column {
    display: table-cell;
    float: none;
    vertical-align: middle;
}

If you don't need IE8 support then you can use CSS3 transform . In your case set top: 50% to your .txt-block and add transform: translateY(-50%); what will move the element 50% of it's height to the top.

JSFiddle DEMO

UPDATE Other good solution is to style your div sa table instead of float ing and use vertical-align: middle; as mentioned here by @Jay.

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