我如何用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>
当前回答
如果你有一个父母的某种高度说,身体{高度:200px} 或如下有父母 div#outer 高度200px,然后添加CSS内容如下
HTML:
<div id="outer">
<div id="centered">Foo foo</div>
</div>
CSS:
#outer{
display: flex;
width: 100%;
height: 200px;
}
#centered {
margin: auto;
}
然后,儿童内容,说 div#中心内容,将垂直或垂直中间,不使用任何位置的CSS。
#centered {
margin: 0px auto;
}
或
#outer{
display: flex;
width: 100%;
height: 200px;
}
#centered {
margin: auto;
}
<div id="outer">
<div id="centered">Foo foo</div>
</div>
演示: https://jsfiddle.net/jinny/p3x5jb81/5/
只添加一个界限显示内部 div 不是 100% 默认:
#outer{ 显示: flex; 宽度: 100%; 高度: 200px; 边界: 1px 固体 #000000; } #centered { 边界: auto; 边界: 1px 固体 #000000; } <div id="outer"> <div id="centered"> Foo foo</div> </div>
DEMO: http://jsfiddle.net/jinny/p3x5jb81/9
其他回答
设置宽度,并设置边缘向左和边缘向右到自动。 这是仅限于水平,但是. 如果你想要两种方式,你只会做这两种方式. 不要害怕尝试; 它不像你会打破任何东西。
我们可以使用下一个CSS的类,允许中心垂直和垂直对其父母的任何元素:
.centerElement{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
最简单的方式之一......
<!DOCTYPE html>
<html>
<head>
<style>
#outer-div {
width: 100%;
text-align: center;
background-color: #000
}
#inner-div {
display: inline-block;
margin: 0 auto;
padding: 3px;
background-color: #888
}
</style>
</head>
<body>
<div id ="outer-div" width="100%">
<div id ="inner-div"> I am a easy horizontally centered div.</div>
<div>
</body>
</html>
最簡單的方式之一是使用顯示器: flex. 外部 div 只需要顯示器 flex, 內部需要範圍: 0 auto 以使其以水平為中心。
要垂直集中,只需在另一个Div中集中一个Div,请查看下面的.inter 类评论。
.wrapper { 显示: flex; /* 添加我们想要的任何高度和宽度 */ 高度: 300px; 宽度: 300px; /* 只是这样你可以看到它是中心 */ 背景: peachpuff; }.inner { /* 中心 水平 */ 边界: 0 自动; /* 中心 垂直 * /* 边界: 0 自动; * /* 中心 * / * 边界: 0 自动; * / } <div class="wrapper"> <div class="inner"> 我是 ho
使用此代码:
<div id="outer">
<div id="inner">Foo foo</div>
</div>
#inner {
width: 50%;
margin: 0 auto;
text-align: center;
}