以div为中心的正确方法

时间:2017-01-07 18:30:38

标签: css

说明

为了测试目的,重新创建(不完全是)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>

提前致谢,
路易斯。

2 个答案:

答案 0 :(得分:0)

如果你问的是如何在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*/
 }

答案 1 :(得分:0)

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

.site-wrapper{
 width:1200px; //you have to give specific width value
 margin: 0 auto;}
相关问题