简体   繁体   English

如何跨浏览器垂直对齐元素?

[英]How to vertical align elements cross-browser?

我正在使用vertical-align: middle属性进行vertical-align: middle它在 Chrome 中有效,但在 IE 中无效。

Supposedly , IE8+ supports vertical-align but IE7- support is buggy.据说,IE8+ 支持vertical-align但 IE7- 支持有问题。 For older browsers, you may want to try setting the element's container's CSS to top: 50% or top: -50% .对于较旧的浏览器,您可能需要尝试将元素的容器的 CSS 设置为top: 50%top: -50%

Have you tried flexbox?你试过 flexbox 吗? It's what I use and I haven't had many (if any) compatibility issues, IE can be a little finicky but it definitely supports it.这是我使用的,我没有遇到很多(如果有的话)兼容性问题,IE 可能有点挑剔,但它绝对支持它。

To center items, you set the container of the elements to display: flex;要居中项目,您可以设置要display: flex;的元素的容器display: flex; and also add align-items: center;并添加align-items: center; to center them vertically within the container.使它们在容器内垂直居中。 You can also center them horizontally with justify-content: center;您还可以使用justify-content: center;它们水平justify-content: center;

You can see it's widely supported here: https://caniuse.com/#feat=flexbox你可以在这里看到它得到了广泛的支持: https : //caniuse.com/#feat=flexbox

只需添加: display: table-cell;

If you want to place a one line text, for example a header title in your box, than use line-height如果要放置一行文本,例如框中的标题标题,请使用line-height

For example with a 200px width and 40px height box:例如宽度为 200 像素、高度为 40 像素的框:

.the_box{
width: 200px;
height: 40px;
line-height: 40px;
}

It's easy, elegant, and cross-browser.它简单、优雅且跨浏览器。 If you have longer text than 200px, this method will not work.如果您的文本长度超过 200 像素,则此方法将不起作用。

I also had this problem, with a calendar table a colleague of mine created.我也有这个问题,我的一个同事创建了一个日历表。 The Calendar viewed nicely in Chrome, Firefox, but the date text was half cut off in the top left corner of each day.日历在 Chrome 和 Firefox 中很好地查看,但日期文本在每天的左上角被截断了一半。 I removed the vertical-alignment property and replaced it with position.我删除了垂直对齐属性并将其替换为位置。 See below.见下文。

Original CSS:原始CSS:

.dayText {
    vertical-align: text-bottom;
}

My CSS Fix:我的 CSS 修复:

.dayText {
    position: relative;
    top: 10px;
    left: 0px;
    height: inherit; 
}

Put

style="valign:middle; vertical-align:middle;"

Newer versions of IE will pick valign:middle and ignore vertical-align:middle .较新版本的 IE 将选择valign:middle并忽略vertical-align:middle

All other browsers like Firefox, Chrome, Safari etc. will pick vertical-align:middle and ignore valign:middle .所有其他浏览器(如 Firefox、Chrome、Safari 等)将选择vertical-align:middle并忽略valign:middle

I had a similar problem我有一个类似的问题

I had the following我有以下

<div>
  <span> some text </span>
</div>

This was all in a header of a table.这一切都在一个表的标题中。

I was able to get around this issue by adding the following to the span我能够通过将以下内容添加到跨度来解决这个问题

<div>
  <span style="position: absolute; padding-top:1px;"> some text </span>
</div>

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

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