我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
当前回答
我已经看到很多和很多答案,他们都是过时的,谷歌已经实施了一个解决这个常见的问题,它将对象的中心字面上在中间,无论发生什么,是的,它是响应性的。
.HTML
...
<div class="parent">
<form> ... </form>
<div> ... </div>
</div>
饰 CSS
.parent {
display: grid;
place-items: center;
}
其他回答
而不是多种包装和/或自动边缘,这个简单的解决方案对我来说工作:
<div style="top: 50%; left: 50%;
height: 100px; width: 100px;
margin-top: -50px; margin-left: -50px;
background: url('lib/loading.gif') no-repeat center #fff;
text-align: center;
position: fixed; z-index: 9002;">Loading...</div>
它将Div放在视图(垂直和水平)的中心,尺寸和调整尺寸,中心背景图像(垂直和水平),中心文本(水平),并保持Div在视图和内容的顶部。
在以前的例子中,他们使用的边界: 0 自动,显示:表和其他答案使用“转换和翻译”。
每个人都知道有一个 <center> 标签,它只是不受 HTML5 支持,但它在 HTML5 中工作。
而且它正在工作,但现在不只是MDN Web Docs,但其他网站建议不要再使用它。 在这里,我可以使用你可以看到MDN Web Docs的笔记。 但无论如何,有这样的方式。
此分類上一篇
它不能集中,如果你不给它一个宽度,否则,它将采取,默认情况下,整个水平空间。
.outer - 完整的宽度.inner - 没有宽度设置(但可以指定最大宽度)
假设计算的元素的宽度为1000像素和300像素。
在.center-helper 中插入.center-helper 创建.center-helper 一个内线区块; 它变成相同的尺寸.center 使其宽 300 像素. 按.center-helper 50% 相对其父母; 此位置其左在 500 像素. 向外. 按.center-helper 50% 相对其父母; 此位置其左在 -150 像素. 向中帮助, 这意味着其左在 500 - 150 = 350 像素。
演示:
好吧,我找到了一个可能适合所有情况的解决方案,但使用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);
})
});