CSS 将 Div 置于另一个(100% 宽度)div 内
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1423651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Center Div inside another (100% width) div
提问by Shadi Almosri
Quite a "simple" problem here and not sure why it's being so complicated.
这里是一个相当“简单”的问题,不知道为什么它如此复杂。
- Have a 100% (width) sized div.
- Have another div positioned in the middle of this div (sized 940px width)
- 有一个 100%(宽度)大小的 div。
- 在这个 div 的中间放置另一个 div(大小为 940px 宽度)
Any ideas? :)
有任何想法吗?:)
回答by geowa4
.parent { text-align: center; }
.parent > .child { margin: 0 auto; width: 900px; }
回答by Virat Kadaru
The below style to the inner div will center it.
内部 div 的以下样式将使其居中。
margin: 0 auto;
回答by Khashayar
for detail info, let's say the code below will make a div aligned center:
有关详细信息,假设下面的代码将使 div 居中对齐:
margin-left: auto;
margin-right: auto;
or simply use:
或简单地使用:
margin: 0 auto;
but bear in mind, the above CSS code only works when you specify a fixed width (not 100%) on your html element. so the complete solution for your issue would be:
但请记住,上述 CSS 代码仅在您在 html 元素上指定固定宽度(不是 100%)时才有效。所以你的问题的完整解决方案是:
.your-inner-div {
margin: 0 auto;
width: 900px;
}
回答by Larsenal
The key is the margin: 0 auto;on the inner div. A proof-of-concept example:
关键是margin: 0 auto; 在内部 div 上。概念验证示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body>
<div style="background-color: blue; width: 100%;">
<div style="background-color: yellow; width: 940px; margin: 0 auto;">
Test
</div>
</div>
</body>
</html>
回答by DeFliGra
.outerdiv {
margin-left: auto;
margin-right: auto;
display: table;
}
Doesn't work in internet explorer 7... but who cares ?
在 Internet Explorer 7 中不起作用……但谁在乎呢?
回答by ScottE
Just add margin: 0 auto;
to the inside div.
只需添加margin: 0 auto;
到内部div。