如何将元素水平和垂直居中,而不考虑其他元素之前和之后?

时间:2017-08-15 19:40:44

标签: html css

https://codepen.io/joshuajazleung/pen/JyONYa

<main>
  <header>Logo</header>
  <div class="center">
    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Labore, laudantium, nam in quia aspernatur animi aut sit eum officia minima cumque obcaecati fugit numquam accusantium distinctio quas recusandae repudiandae reiciendis.</p>
  </div>
</main>

html, body, main {
  padding: 0;
  margin: 0;
}

main {
  height: 600px;
  width: 100%;
  background: red;
}

header {
  height: 100px;
}

.center {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

在这里,我想在.center元素上使用flexbox水平和垂直地居中<main> div。但由于存在<header>.center会稍微向下移动,因为<header>占用<main>上的一些空格。我怎样才能实现绝对居中?

3 个答案:

答案 0 :(得分:1)

将标题设置为绝对标题,以便所有其他元素忽略它。

header {
  height: 100px;
  width: 100%;
  position: absolute;
  background: green;
}

html,
body,
main {
  padding: 0;
  margin: 0;
}

main {
  height: 600px;
  width: 100%;
  background: red;
}

header {
  height: 100px;
  width: 100%;
  position: absolute;
  background: green;
}

.center {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
<main>
  <header>Logo</header>
  <div class="center">
    <div>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Labore, laudantium, nam in quia aspernatur animi aut sit eum officia minima cumque obcaecati fugit numquam accusantium distinctio quas recusandae repudiandae reiciendis.</div>
  </div>
</main>

答案 1 :(得分:0)

您可以尝试将position: absolute添加到标题中。这将使标头脱离正常流程,以便.center元素将在整个<main>元素中居中。

答案 2 :(得分:0)

这样可行。

<main>
  <header>Logo</header>
  <div class="center">
    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Labore, laudantium, nam in quia aspernatur animi aut sit eum officia minima cumque obcaecati fugit numquam accusantium distinctio quas recusandae repudiandae reiciendis.</p>
  </div>
</main>
for(let i = 0 ; i < 50 ; i++) {
    buildfire.datastore.insert({
        name: "Address" + i
        ,address: i + " " + (i % 2 ? "Main ":"4th ") + (i % 3 ? "ave":"st" )
    },function(){});
}