如何跨浏览器垂直对齐元素?
我正在使用 vertical-align: middle
属性进行垂直对齐,它在 Chrome 中工作,但在 IE 中不起作用。
I am doing vertical alignment using vertical-align: middle
property its working in Chrome but not in IE.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你尝试过弹性盒子吗?这就是我使用的,我没有遇到很多(如果有的话)兼容性问题,IE 可能有点挑剔,但它绝对支持它。
要居中项目,请将元素的容器设置为
display: flex;
并添加align-items: center;
以将它们在容器内垂直居中。您还可以使用justify-content: center;
将它们水平居中。您可以看到它在这里得到了广泛支持:https://caniuse.com/#feat=flexbox
Have you tried 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.
To center items, you set the container of the elements to
display: flex;
and also addalign-items: center;
to center them vertically within the container. You can also center them horizontally withjustify-content: center;
You can see it's widely supported here: https://caniuse.com/#feat=flexbox
据说,IE8+支持
vertical-align
,但IE7-支持越野车。对于较旧的浏览器,您可能需要尝试将元素容器的 CSS 设置为top: 50%
或top: -50%
。Supposedly, IE8+ supports
vertical-align
but IE7- support is buggy. For older browsers, you may want to try setting the element's container's CSS totop: 50%
ortop: -50%
.如果您想在框中放置单行文本,例如标题标题,请使用
line-height
例如,使用 200 像素宽度和 40 像素高度的框:
它简单、优雅且跨域浏览器。如果文本长度超过 200 像素,此方法将不起作用。
If you want to place a one line text, for example a header title in your box, than use
line-height
For example with a 200px width and 40px height box:
It's easy, elegant, and cross-browser. If you have longer text than 200px, this method will not work.
只需添加以下内容:
显示:表格单元格;
Simply add this:
display: table-cell;
新
版本的 IE 将选择
valign:middle
并忽略vertical-align:middle
。所有其他浏览器(例如 Firefox、Chrome、Safari 等)都会选择
vertical-align:middle
并忽略valign:middle
。Put
Newer versions of IE will pick
valign:middle
and ignorevertical-align:middle
.All other browsers like Firefox, Chrome, Safari etc. will pick
vertical-align:middle
and ignorevalign:middle
.我也遇到了这个问题,我的一位同事创建了一个日历表。日历在 Chrome、Firefox 中显示效果很好,但每天左上角的日期文本被截断了一半。我删除了垂直对齐属性并将其替换为位置。见下文。
原始 CSS:
我的 CSS 修复:
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. I removed the vertical-alignment property and replaced it with position. See below.
Original CSS:
My CSS Fix:
我遇到了类似的问题
,我有以下问题
,这全部都在表的标题中。
我可以通过将以下内容添加到范围来解决这个问题
I had a similar problem
I had the following
This was all in a header of a table.
I was able to get around this issue by adding the following to the span