Html CSS如何水平居中div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14821277/
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 05:32:42  来源:igfitidea点击:

CSS How to center a div horizontally

htmlcss

提问by Kobojunkie

I am working on centering a div horizontally. I have the following code to center my div in the body tag both vertically and horizontally, but seems just the vertical piece works. How can I get the horizontal piece to work as well. Thanks in advance.

我正在水平居中 div。我有以下代码可以垂直和水平地将我的 div 居中在 body 标签中,但似乎只是垂直部分有效。我怎样才能让水平部分也能工作。提前致谢。

body
{
    background-color: #081418;
    font-size: .75em;
    font-family: Verdana, Helvetica, Sans-Serif;
    margin: 0;
    padding: 0;
    color: #696969; 
    text-align: center;
}

.OuterRim
{
    border:5px solid #99D7C0;
    height: 97%;
    width: 85%;
    /*center aligning*/ 
    display: block;
    text-align: left;
    margin: 0px auto;

}

回答by MGDTech

Take a look here at this tutorial to learn how to do it. You need to have an element with a fixed width. This can be done with css or jquery.

就拿这里看看在本教程学习如何做到这一点。你需要有一个固定宽度的元素。这可以用 css 或 jquery 来完成。

回答by user2055453

margin:0px auto;

if the div is positioned absolute or fixed then use

如果 div 定位为绝对或固定,则使用

margin:0px auto;
left:0;
right:0;

回答by Raphael Rafatpanah

http://jsfiddle.net/persianturtle/jm7vF/1/

http://jsfiddle.net/persianturtle/jm7vF/1/

I believe this may solve your problem if I understand it correctly.

如果我理解正确,我相信这可以解决您的问题。

I placed a container div around your div and put percentage margins all around.

我在你的 div 周围放置了一个容器 div,并在四周放置了百分比边距。

.container {
height: 50%;
margin: 25% 25% 25% 25%;
}

Hope this helps!

希望这可以帮助!