简体   繁体   English

当容器高度未知时,居中垂直对齐元素

[英]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/ http://machinas.com/wip/hugoboss/sensitive-img/

The height depends on the size of the image really so I can't really set a height of the column. 高度实际上取决于图像的大小,因此我无法真正设置列的高度。

HTML 的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 的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. 您需要删除大6列div上的浮点数,并在中间添加垂直对齐方式,还应将其显示为表格单元而不是表格。 The row is acting as a table. 该行充当表格。 See css below; 参见下面的css;

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

If you don't need IE8 support then you can use CSS3 transform . 如果不需要IE8支持,则可以使用CSS3 transform In your case set top: 50% to your .txt-block and add transform: translateY(-50%); 在您的情况下,请top: 50% .txt-block top: 50%并添加transform: translateY(-50%); what will move the element 50% of it's height to the top. 什么将元素的高度的50%移到顶部。

JSFiddle DEMO JSFiddle演示

UPDATE Other good solution is to style your div sa table instead of float ing and use vertical-align: middle; UPDATE另一个好的解决方案是设置div表的样式而不是float样式,并使用vertical-align: middle; as mentioned here by @Jay. 正如@Jay 在这里提到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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