我如何用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>
当前回答
最简单的方式之一......
<!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>
其他回答
#outer { 显示: 网; justify- 内容: 中心; } <div id="outer"> <div id="inner">hello</div> </div> 在这里输入代码
克里斯·科伊尔(Chris Coyier)在他的博客上写了一篇关于“在未知中集中”的好文章,这是一个多种解决方案的环节,我发表了一个没有发表在这个问题上,它有更多的浏览器支持,而不是Flexbox解决方案,你不使用显示:表;这可能会破坏其他事情。
/* This parent can be any width and height */
.outer {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.outer:before {
content: '.';
display: inline-block;
height: 100%;
vertical-align: middle;
width: 0;
overflow: hidden;
}
/* The element to be centered, can
also be of any width and height */
.inner {
display: inline-block;
vertical-align: middle;
width: 300px;
}
如果您不想设置固定宽,并且不需要额外的边界,则将显示器添加到您的元素中: inline-block。
你可以使用:
#element {
display: table;
margin: 0 auto;
}
您可以使用 CSS Flexbox。
#inner {
display: flex;
justify-content: center;
}
您可以在此链接中了解更多信息: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
我最近找到了一个方法:
#outer {
position: absolute;
left: 50%;
}
#inner {
position: relative;
left: -50%;
}
两个元素必须是相同的宽度,以便正常运作。