使用margin时div不居中:auto; (引导程序)

时间:2018-12-30 10:08:44

标签: html css twitter-bootstrap

我有一个引导模板网站上的工作示例网站,并且正在分析代码以了解他们是如何创建的。即他们如何将文本居中放在this tutoral的第一页上。该代码段的代码是

<header class="masthead text-center text-white d-flex"> <!-- Background image set here -->
    <div class="container m-auto">
        <div class="row">
            <div class="col-lg-10 mx-auto">
                   ...
            </div>
            <div class="col-lg-8 mx-auto">
                   ...
            </div>
        </div>
    </div>
</header>

因此,我注意到m-auto正在对中。但是,当我尝试为自己重新创建它并创建此基本代码时,

 <style>
    #frontpage {
      height: 100vh;
      width: 100vw;
    }
  </style>

<section id="frontpage">
  <div class="container m-auto">
    <div class="row">
      <div class="col-8">
        <h1> YOU CAN DO IT </h1>
      </div>
      <div class="col-8">
        <h1> I should be centered </h1>
      </div>
    </div>
  </div>
</section>

它根本没有居中。 我在这里忘记了什么?

我怀疑容器位于其父容器的中央,从而占据了页面。

2 个答案:

答案 0 :(得分:0)

您已经复制了代码,但是如果猜对了,样式将不包含在其中。无论如何,我已更正,请尝试此。

 <style>
        #frontpage {
          height: 100vh;
          width: 100%;
        }

.center-me{
    margin: auto;
    width: 60%;
    text-align: center;
}
      </style>

    <section id="frontpage">
            <div class="center-me">
                    <div >
                      <h1> YOU CAN DO IT </h1>
                    </div>
                    <div >
                      <h1> I should be centered </h1>
                    </div>
      </div>
    </section>

答案 1 :(得分:0)

这是你的追随者吗?
版本1

https://codepen.io/panchroma/pen/YdEWZJ

HTML

<section id="frontpage">
  <div class="container m-auto">
    <div class="row">
        <div class="col-8">
        <h1> YOU CAN DO IT </h1>
      </div>
      <div class="col-8">
        <h1> I should be centered </h1>
      </div>
      </div>
  </div>
</section>

CSS

#frontpage{
  background-color:pink;
  height: 100vh;
  width: 100vw;
}
.col-8{
  border:1px solid grey;
  margin-left:auto !important;
  margin-right:auto !important;
  text-align:center;
}

版本2
这也会使文本垂直居中
https://codepen.io/panchroma/pen/KbygzX

HTML

<section id="frontpage">
  <div class="container m-auto">
    <div class="row vert-align">
          <div class="col-8">
        <h1>YOU CAN DO IT</h1>
      </div>
      <div class="col-8">
        <h1> I should be centered </h1>
      </div>
      </div>
  </div>
</section>  

CSS

#frontpage{
  background-color:pink;
  height: 100vh;
  width: 100vw;
}
.col-8{
  margin-left:auto !important;
  margin-right:auto !important;
  text-align:center;
}

.row.vert-align{
  position: absolute;
  top: 50%;
  left:50%;
  -ms-transform: translateY(-50%);
  transform: translate(-50%, -50%);
}
相关问题