在CSS中垂直居中元素 [英] Vertically center elements in CSS

查看:90
本文介绍了在CSS中垂直居中元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个元素并排。元件2小于元件1.两个元件不具有固定的高度。我需要垂直地居中元素2.如何使用CSS实现这一点?



编辑:



我到目前为止:

 < div id =containerstyle =width:100%;> 
< div id =img1style =float:left;>
< img src =image1.jpg... />
< / div>
< div id =img2style =float:right;>
< img src =image2.jpg... />
< / div>
< / div>

img1的高度将始终大于img2的高度。我想要img2垂直中心对齐。希望这澄清了我想要完成的工作。

解决方案

最直接和干净的方法是使用 display:table 和vertical-align。但是,IIRC(一直以来,因为我是在浏览器兼容性问题)支持 display:table 和朋友不存在...一些常见的版本的IE , 也许?无论如何,如果 display:table 被忽略,添加其他规则来做足够的后备。

 < div id =containerstyle =display:table;> 
< div id =div1style =display:table-cell; vertical-align:middle;>
< img id =img1src =image1.jpg/>
< / div>
< div id =div2style =display:table-cell; vertical-align:middle;>
< img id =img2src =image2.jpg/>
< / div>
< / div>

(当然样式应该在样式表中;这只是与原始示例匹配,而不是了解用例。)



显示值 table-row table-cell 基本上与HTML code>, tr td ,但您可以省略其中任何一个这里,使用 table-cell s直接在中),布局引擎将做明智的事情。 p>

I have two elements side-by-side. Element 2 is smaller than Element 1. Both elements do not have a fixed height. I need to vertically center Element 2. How do I achieve this using CSS?

Edited:

This is what I have so far:

<div id="container" style="width: 100%;">
    <div id="img1" style="float: left;">
        <img src="image1.jpg".../>
    </div>
    <div id="img2" style="float: right;">
        <img src="image2.jpg".../>
    </div>
</div>

img1's height will always be greater than img2's height. I want img2 to be aligned vertically-center. Hopefully this clarifies what I am trying to accomplish.

解决方案

The most straightforward and clean way to do it is to use display: table and vertical-align. However, IIRC (it's been a while since I was up on browser compatibility issues) support for display: table and friends is absent from ... some common-then version of IE, perhaps? Anyway, adding other rules to make an adequate fallback if the display: table is ignored might be good.

<div id="container" style="display: table;">
    <div id="div1" style="display: table-cell; vertical-align: middle;">
        <img id="img1" src="image1.jpg" />
    </div>
    <div id="div2" style="display: table-cell; vertical-align: middle;">
        <img id="img2" src="image2.jpg" />
    </div>
</div>

(Of course the styles ought to be in a stylesheet; this is just matching your original example and not knowing the use case.)

The display values table, table-row, and table-cell basically perform exactly like HTML table, tr, and td, but you are permitted to omit any of them (as I do here, using table-cells directly within tables) and the layout engine will do the sensible thing.

这篇关于在CSS中垂直居中元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆