且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在另一个 div 中垂直居中一个 div

更新时间:2023-10-09 10:13:10

tl;博士

垂直对齐中间有效,但您必须在父元素上使用 table-cell 并在子元素上使用 inline-block.

Vertical align middle works, but you will have to use table-cell on your parent element and inline-block on the child.

此解决方案不适用于 IE6 &7.
你的方式是更安全的方式.
但由于您使用 CSS3 和 HTML5 标记了您的问题,我认为您不介意使用现代解决方案.

This solution is not going to work in IE6 & 7.
Yours is the safer way to go for those.
But since you tagged your question with CSS3 and HTML5 I was thinking that you don't mind using a modern solution.

经典解决方案(表格布局)

这是我最初的答案.它仍然可以正常工作,并且是获得最广泛支持的解决方案.表格布局将 影响您的渲染性能,因此我建议您使用更现代的解决方案之一.

This was my original answer. It still works fine and is the solution with the widest support. Table-layout will impact your rendering performance so I would suggest that you use one of the more modern solutions.

这里是一个例子

测试于:

  • FF3.5+
  • FF4+
  • Safari 5+
  • Chrome 11+
  • IE9+

HTML

<div class="cn"><div class="inner">your content</div></div>

CSS

.cn {
  display: table-cell;
  width: 500px;
  height: 500px;
  vertical-align: middle;
  text-align: center;
}

.inner {
  display: inline-block;
  width: 200px; height: 200px;
}

现代解决方案(变换)

由于变换现在得到相当好的支持,所以有一种更简单的方法.

Since transforms are fairly well supported now there is an easier way to do it.

CSS

.cn {
  position: relative;
  width: 500px;
  height: 500px;
}

.inner {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%,-50%);
  width: 200px;
  height: 200px;
}

演示

♥我最喜欢的现代解决方案(flexbox)

我开始越来越多地使用 flexbox 它现在也得到很好的支持 这是迄今为止最简单的方法.

I started to use flexbox more and more its also well supported now Its by far the easiest way.

CSS

.cn {
  display: flex;
  justify-content: center;
  align-items: center; 
}

演示

更多示例和可能性:比较一页上的所有方法