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

2022-01-30 00:00:00 html css

我想将另一个 div 中的 div 居中.

I want to center a div which is inside another div.

<div id="outerDiv">
    <div id="innerDiv">
    </div>
</div>

这是我目前使用的 CSS.

This is the CSS I am currently using.

    #outerDiv {
        width: 500px;
        height: 500px;
        position: relative;
    }
    
    #innerDiv {
        width: 284px;
        height: 290px;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -147px;
        margin-left: -144px;
    }

如您所见,我现在使用的方法取决于 #innerDiv 的宽度和高度.如果宽度/高度发生变化,我将不得不修改 margin-topmargin-left 值.是否有任何通用解决方案可用于使 #innerDiv 独立于其大小居中?

As you can see, the approach I use now depends on the width and height of #innerDiv. If the width/height changes, I will have to modify the margin-top and margin-left values. Is there any generic solution that I can use to center the #innerDiv independently of its size?

我发现使用 margin: auto 可以将 #innerDiv 水平对齐到中间.但是垂直对齐呢?

I figured out that using margin: auto can horizontally align the #innerDiv to the middle. But what about vertical alignment?

推荐答案

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; 
}

演示

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

相关文章