我如何用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. 使用此一个:
<div id="outer" style="width:100%">
<div id="inner" style="display:table;margin:0 auto;">Foo foo</div>
</div>
其他回答
使用 Sass (SCSS合成) 你可以用混合物做到这一点:
与翻译
// Center horizontal mixin
@mixin center-horizontally {
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
}
// Center horizontal class
.center-horizontally {
@include center-horizontally;
}
在HTML标签中:
<div class="center-horizontally">
I'm centered!
</div>
请记住添加位置:相对;到母 HTML 元素。
与Flexbox
使用Flex,你可以这样做:
@mixin center-horizontally {
display: flex;
justify-content: center;
}
// Center horizontal class
.center-horizontally {
@include center-horizontally;
}
在HTML标签中:
<div class="center-horizontally">
<div>I'm centered!</div>
</div>
试试这个CodePen!
最简单的方式:
#outer { 宽度: 100%; 文本平衡:中心; } #inner { 边缘:自动; 宽度: 200px; } <div id="outer"> <div id="inner">Blabla</div> </div>
我只是使用最简单的解决方案,但它在所有浏览器工作:
<!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>
Firefox 和 Chrome:
<div style="width:100%;"> <div style="width: 50%; margin: 0px auto;"> 文本</div> </div>
适用于 Internet Explorer、Firefox 和 Chrome:
<div style="width:100%; text-align:center;"> <div style="width: 50%; margin: 0px auto; text-align:left;">Text</div> </div>
文本同步:属性是现代浏览器的可选,但在 Internet Explorer Quirks 模式中需要继承浏览器的支持。
它不能集中,如果你不给它一个宽度,否则,它将采取,默认情况下,整个水平空间。