我如何用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>
当前回答
button {
margin: 0 auto;
width: fit-content;
display: block;
}
// container should have set width (for example 100%)
其他回答
例如,请参见此链接和下面的剪辑:
div#outer { 高度: 120px; 背景颜色: 红色; } div#内部 { 宽度: 50%; 高度: 100%; 背景颜色: 绿色; 边缘: 0 自动; 文本平衡: 中心; /* 文本平衡到中心垂直. */ 线高度: 120px; /* 文本平衡到中心垂直。
如果你有很多孩子在一个父母之下,那么你的CSS内容应该像这个例子。
HTML 内容看起来喜欢此:
<div id="outer" style="width:100%;">
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> Foo Text </div>
</div>
然后,看看这个例子在Fiddle。
使用:
<div id="parent">
<div class="child"></div>
</div>
风格:
#parent {
display: flex;
justify-content: center;
}
如果你想把它集中在水平上,你应该写下如下:
#parent {
display: flex;
justify-content: center;
align-items: center;
}
我只是使用最简单的解决方案,但它在所有浏览器工作:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>center a div within a div?</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#outer{
width: 80%;
height: 500px;
background-color: #003;
margin: 0 auto;
}
#outer p{
color: #FFF;
text-align: center;
}
#inner{
background-color: #901;
width: 50%;
height: 100px;
margin: 0 auto;
}
#inner p{
color: #FFF;
text-align: center;
}
</style>
</head>
<body>
<div id="outer"><p>this is the outer div</p>
<div id="inner">
<p>this is the inner div</p>
</div>
</div>
</body>
</html>
试试这:
<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 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 的老式同步的老式浏览器,这里是一个很好的地方去看。