使div居中的正确方法[重复]

Posted

技术标签:

【中文标题】使div居中的正确方法[重复]【英文标题】:Proper way to center a div [duplicate] 【发布时间】:2017-05-22 08:30:57 【问题描述】:

说明

为了测试目的,重新创建(不完全是)this site 的样式,下面的代码是正确的方法吗?我的意思是,这会是常见/最好的方法吗?

对不起,如果问题太简单了,但这是因为我发现了很多使用displaypositiontopleft 等的模板,因为我是网络开发新手,我想我可能做错了什么——因为我用了几行代码来做到这一点。

ps:我没有使用 text-align: center,因为我使用的是 Bootstrap 的 text-center 类,我认为它也是如此。

代码

body 
    background-color: #2098D1 !important;


h1, p 
    color: white !important;


.site-wrapper 
    margin-top: 230px;


.site-wrapper p 
    margin-top: 15px;
<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <title>Example</title>
    <link rel="stylesheet" href="main.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

</head>

<body>

    <div class="site-wrapper text-center">
        <h1>Responsive Front-end Development</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>
    </div>

</body>

</html>

提前致谢, 路易斯。

【问题讨论】:

我觉得很好 【参考方案1】:

如果您要问的是如何在 div 中垂直居中内容,您可以使用display: flex;

试试这个:

.site-wrapper 
     height: 75%;
     display: flex;
     align-items: center; /*Horizontally centers content*/
     justify-content: center; /*Vertically centers content*/
     flex-direction: column; /* Makes content in div to flow under instead of side by side*/
 

【讨论】:

【参考方案2】:

div元素是块元素,因此如果你想水平居中最简单的方法是使用margin auto方法。

.site-wrapper
 width:1200px; //you have to give specific width value
 margin: 0 auto;

【讨论】:

以上是关于使div居中的正确方法[重复]的主要内容,如果未能解决你的问题,请参考以下文章

CSS 如何使DIV层水平居中

正确居中

CSS中怎么让DIV居中亲自实验得出的结论

如何使 div 垂直居中? [复制]

如何使文字在div中水平和垂直居中的css代码

使用 CSS 更智能地居中 div [重复]