【问题标题】:Proper way to center a div [duplicate]使div居中的正确方法[重复]
【发布时间】: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>

提前致谢,
路易斯。

【问题讨论】:

  • 我觉得很好

标签: css


【解决方案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;}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2013-02-27
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多