垂直水平居中: 最新和最旧的酷方法

本文介绍了两种在CSS中实现元素垂直和水平居中的方法:一种利用表格属性display:table和vertical-align:middle,适用于IE8及以上浏览器;另一种使用现代布局方法Flexbox和CSS Grid,更加简洁高效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


This is just a little observation about old and new. One of the trickier things related to centering in CSS is when you need to center both vertically and horizontally and you don't know the width or height of what you are centering. Vertical centering being the extra tricky of the two.

Believe it or not, there was a way to do that even in IE 8. The trick was taking advantage of display: table; and that tables had this other property, vertical-align: middle;, which could be used for vertical centering.

Say all you wanted to do was center a sentence perfectly in the middle of the browser window:

...
<body>
  <span>
    Centered vertically and horizontally.
  </span>
</body>
...

You could do that like this:

html, body {
  margin: 0;
  height: 100%;
}
body {
  display: table;
  width: 100%;
}
body > span {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

That might be the oldest trick in the Book of CSS Centering. Here it is working in IE 8:

Today we have more modern layout methods. Flexbox! CSS grid!

Here's accomplishing the same thing with the most modern methods available:

body {
  display: grid;
  height: 100vh;
  margin: 0;
  place-items: center center;
}

We don't even need to touch the span there! This is so cutting edge, in fact, that Microsoft Edge, which supports CSS grid, doesn't support place-items yet. You'd have to use align-items: center; and justify-content: center; instead.

Always movin'.

The post Centering: The Newest Coolest Way vs. The Oldest Coolest Way appeared first on CSS-Tricks.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值