CSS 将一个 div 放在一个部分中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16528305/
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 a div in a section
提问by Don P
I'm trying to center a <div>
in <section>
. Setting margin-left and margin-right to auto
isn't working (my usual method). What am I forgetting?
我试图居中<div>
在<section>
。将 margin-left 和 margin-right 设置auto
为不起作用(我常用的方法)。我忘记了什么?
jsFiddle of the problem: http://jsfiddle.net/veWKh/
问题的jsFiddle:http: //jsfiddle.net/veWKh/
回答by Niels
Setting the width, otherwise the div is display block and has a width of 100%: fiddle: http://jsfiddle.net/veWKh/1/
设置宽度,否则div是显示块,宽度为100%:fiddle: http://jsfiddle.net/veWKh/1/
CSS:
CSS:
section {
background-color: rgba(0,0,0,0.2);
}
div {
margin-left: auto;
margin-right: auto;
width: 100px;
}
回答by Kevin Lynch
For margin:auto
to work you need to give the div
a set width
eg:
为了margin:auto
工作,您需要提供div
一组,width
例如:
div {
width:100px;
margin: 0 auto;
}
回答by Web User
Try it
尝试一下
section {
background-color: rgba(0,0,0,0.2);
}
div {
margin-left: auto;
margin-right: auto;
text-align: center;
}
回答by Sanjaya Liyanage
set the width first.Other wise it will occupy the full space and setting margins will not work
首先设置宽度。否则它将占据整个空间并且设置边距将不起作用
div {
width:30em;
margin-left: auto;
margin-right: auto;
}
回答by Antarr Byrd
This width of your div is not limited so what you are doing is not visible.
你的 div 的宽度没有限制,所以你在做什么是不可见的。
div {
display:block;
width:50%;
background-color: #ffffff;
margin: 0 auto;
}
回答by Anickyan
This works perfectly:
这完美地工作:
section
{
text-align: center;
}
This will make everything centered, though. Otherwise you can just do this:
不过,这将使一切居中。否则你可以这样做:
div
{
display:block;
text-align:center;
margin: auto;
}