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

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

当前回答

好吧,我找到了一个可能适合所有情况的解决方案,但使用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);
  })
});

其他回答

你可以做这样的事情

#container {
   display: table;
   width: <width of your container>;
   height: <height of your container>;
}

#inner {
   width: <width of your center div>;
   display: table-cell;
   margin: 0 auto;
   text-align: center;
   vertical-align: middle;
}

這也會垂直調整 #內部. 如果你不願意,移除顯示器和垂直調整的特性;

在以前的例子中,他们使用的边界: 0 自动,显示:表和其他答案使用“转换和翻译”。

每个人都知道有一个 <center> 标签,它只是不受 HTML5 支持,但它在 HTML5 中工作。

而且它正在工作,但现在不只是MDN Web Docs,但其他网站建议不要再使用它。 在这里,我可以使用你可以看到MDN Web Docs的笔记。 但无论如何,有这样的方式。

此分類上一篇

CSS3:

您可以在父母容器上使用以下风格平等地分配儿童元素:

display: flex;
justify-content: space-between;  // <-- space-between or space-around

关于正当内容的不同价值观的好示范。

此分類上一篇

CanIUse:浏览器兼容性

尝试一下:

#containerdiv {显示: flex; justify-content: space-between; } #containerdiv > div {背景颜色:蓝色;宽度: 50px;颜色:白色;文本平行:中心; } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="containerdiv"> <div>88</div> <div>77</

试试这:

<div id="a">
    <div id="b"></div>
</div>

CSS:

#a{
   border: 1px solid red;
   height: 120px;
   width: 400px
}

#b{
   border: 1px solid blue;
   height: 90px;
   width: 300px;
   position: relative;
   margin-left: auto;
   margin-right: auto;
}

使用下面的 CSS 内容为 #inner div:

#inner {
  width: 50%;
  margin-left: 25%;
}

我主要使用这个CSS内容为中心Divs。