我如何用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>
当前回答
我在各个项目中使用的最好是
<div class="outer">
<div class="inner"></div>
</div>
.outer{
width: 500px;
height: 500px;
position: relative;
background: yellow;
}
.inner{
width: 100px;
height: 100px;
background:red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Fiddle 链接
其他回答
一些海报已经提到CSS 3的中心方式使用显示:盒子。
这个合成是过时的,不应该再使用。
因此,仅仅是为了完整性,这里是使用灵活盒子布局模块在CSS 3中集中最新的方式。
所以,如果你有简单的标签如:
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
...你想把你的物品集中在盒子内,这里是你需要的父母元素(.box):
.box {
display: flex;
flex-wrap: wrap; /* Optional. only if you want the items to wrap */
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
.box { 显示: flex; flex-wrap: wrap; /* 可选. 只有如果您想要的物品将 wrap */ 定义内容: 中心; /* 为水平调整 */ 定义项目: 中心; /* 为垂直调整 */ } * { 边界: 0; 粘贴: 0; } html, 身体 { 高度: 100%; }.box { 高度: 200px; 显示: flex; flex-wrap: 定义内容: 中心; 定义项目: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容
如果您需要支持使用 flexbox 的老式同步的老式浏览器,这里是一个很好的地方去看。
中心一个元素,不需要动态高度和宽度的旋转器/父母
没有副作用:它不会限制一个集中元素的宽度低于视门宽度,当使用Flexbox中的边缘在一个集中元素内
position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%));
垂直 + 垂直中心,如果其高度与宽度相同:
position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
Flexbox 中心 垂直和垂直 中心 调整一个元素
.wrapper {边界: 1px 固体 #678596; 最大宽度: 350px; 边界: 30px 自动;}.parentClass { 显示: flex; 定义内容:中心; 平衡元素:中心; 高度: 300px;}.parentClass div { 边界: 5px; 背景: #678596; 宽度: 50px; 线高度: 50px; 文本平衡:中心; 字体大小: 30px; 颜色: #fff;} <h1>Flexbox 中心 垂直和垂直 中心 平衡元素</h1> <h2>j
可以用很多方法来做到这一点,很多男孩/男孩的答案是正确的,并且工作得很好,我会给一个更不同的模式。
在HTML文件中
<div id="outer">
<div id="inner">Foo foo</div>
</div>
在 CSS 文件中
#outer{
width: 100%;
}
#inner{
margin: auto;
}
我已经看到很多和很多答案,他们都是过时的,谷歌已经实施了一个解决这个常见的问题,它将对象的中心字面上在中间,无论发生什么,是的,它是响应性的。
.HTML
...
<div class="parent">
<form> ... </form>
<div> ... </div>
</div>
饰 CSS
.parent {
display: grid;
place-items: center;
}