我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

当前回答

1. 中心一个区块级元素使用自动为水平边界

二、中心区块级元素,使用垂直边缘的卡尔克

.outer { 位置: 相对; 宽度: 300px; 高度: 180px; 背景颜色: rgb(255, 0, 0); }.inner { 位置: 绝对; 左: 50%; 宽度: 150px; 高度: 180px; 背景颜色: rgb(255, 255, 0); transform: translateX(-75px); } <div class="outer"> <div class="inner"></div> </div>

7、使用显示器中心一个元素:桌面、板块和盒子

8. 使用显示器中心一个元素: flex 和 justify 内容: 中心

.outer { 显示: 网络; 正当标题: 中间; 宽度: 300px; 高度: 180px; 背景颜色: rgb(255, 0, 0); }.inner { 宽度: 150px; 背景颜色: rgb(255, 255, 0); } <div class="outer"> <div class="inner"></div> </div>

其他回答

专注于水平

演示:


以垂直和垂直为中心

在我的经验中,将盒子垂直和水平中心的最佳方式是使用额外的容器,并应用以下属性:

外部容器:

内部容器:

内容盒子:

.outer 容器 { 显示: 表; 宽度: 100%; 高度: 120px; 背景: #CCC; }. 内部容器 { 显示: 表 细胞; 垂直平面: 中间; 文本平面: 中间; }.centered 内容 { 显示: inline-block; 背景: #FFF; padding: 20px; 边界: 1px 固体 #000; } <div class="outer-container"> <div class="inter-container"> <div class="centered-content">

再看这个Fiddle吧!

方法1:使用边缘财产

如果元素不是区块级元素,然后添加显示器:区块属性到它。

#outer { 显示: flex; justify- 内容: 中心; 背景颜色: 银色; } #inner { 背景颜色: #f07878; } <div id="outer"> <div id="inner"> Foo foo</div> </div>

这是一个经典的方法,以中心元素. 设置位置:相对外部元素. 设置内部元素的位置为绝对和左: 50%. 这将推动内部元素从外部元素的中心开始. 现在使用转变属性和设置转变: 翻译X(-50%) 这将使元素的中心水平。

好吧,我找到了一个可能适合所有情况的解决方案,但使用JavaScript:

这里是结构:

<div class="container">
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
</div>

此分類上一篇: JavaScript snippet:

$(document).ready(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

如果你想用它在一个响应性方法,你可以添加以下:

$(window).resize(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

我创建了这个例子,以表明如何垂直和水平地调整。

这个代码基本上就是这样:

#outer {
 position: relative;
}

和...

#inner {
  margin: auto;
  position: absolute;
  left:0;
  right: 0;
  top: 0;
  bottom: 0;
}

它会留在中心,即使你重新启动屏幕。

如果有人想要一个 jQuery 解决方案的中心调整这些 divs:

$(window).bind("load", function() {
    var wwidth = $("#outer").width();
    var width = $('#inner').width();
    $('#inner').attr("style", "padding-left: " + wwidth / 2 + "px; margin-left: -" + width / 2 + "px;");
});