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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:50:52  来源:igfitidea点击:

Center a div in a section

cssmargincentering

提问by Don P

I'm trying to center a <div>in <section>. Setting margin-left and margin-right to autoisn'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:autoto work you need to give the diva set widtheg:

为了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;
}