我如何用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 id="outer">
<div id="inner">Foo foo</div>
</div>
CSS
#outer {
text-align: center;
}
#inner{
display: inline-block;
}
其他回答
我最近发现的一件好事,混合了线高度+垂直平行和50%左线技巧的使用,你可以在另一个动态尺寸的盒子内集中一个动态尺寸的盒子,在水平和垂直,使用纯粹的CSS。
请注意,您必须使用在现代浏览器 + Internet Explorer 8 中测试的 spans(和 inline-block)。
<h1>Center dynamic box using only css test</h1>
<div class="container">
<div class="center">
<div class="center-container">
<span class="dyn-box">
<div class="dyn-head">This is a head</div>
<div class="dyn-body">
This is a body<br />
Content<br />
Content<br />
Content<br />
Content<br />
</div>
</span>
</div>
</div>
</div>
CSS:
.container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
overflow: hidden;
}
.center {
position: absolute;
left: 50%;
top: 50%;
}
.center-container {
position: absolute;
left: -2500px;
top: -2500px;
width: 5000px;
height: 5000px;
line-height: 5000px;
text-align: center;
overflow: hidden;
}
.dyn-box {
display: inline-block;
vertical-align: middle;
line-height: 100%;
/* Purely asthetic below this point */
background: #808080;
padding: 13px;
border-radius: 11px;
font-family: arial;
}
.dyn-head {
background: red;
color: white;
min-width: 300px;
padding: 20px;
font-size: 23px;
}
.dyn-body {
padding: 10px;
background: white;
color: red;
}
请参见这里的例子
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</
你可以以不同的方式做到这一点. 请参见下面的例子:
1. First Method
#outer {
text-align: center;
width: 100%;
}
#inner {
display: inline-block;
}
2. Second method
#outer {
position: relative;
overflow: hidden;
}
.centered {
position: absolute;
left: 50%;
}
可以使用中心标签为方便
<div id="outer">
<center>
<div id="inner">Foo foo</div>
</center>
</div>
您可以使用链接 https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview
.outer{
display: table;
width: 100%;
height: 100%;
}
.inner {
vertical-align: middle;
}
参考 https://v4-alpha.getbootstrap.com/例子/覆盖/