如何从顶部显示居中的div?

时间:2016-05-26 19:13:57

标签: html css css3 flexbox

我有这段代码:

<div id="background">
  <div id="box">
    <ol>
    <li>asdf asdf asdf</li>
    ...
    </ol>
  </div>
</div>

CSS:

html, body {
  height: 100%;
  margin: 0px;
}
#background {
  display: flex;
  align-items: center;
  height: 100%;
}
#box {
  background-color: yellow;
  margin: 0 auto;
  width: 200px;
}

https://jsfiddle.net/tfuu63et/

如果列表很短,它可以正常工作。但如果这很长,我就无法在列表顶部看到一些项目。

我该如何修复?

3 个答案:

答案 0 :(得分:0)

你试过align-items: flex-start吗?这似乎得到了你想要的结果。

除非您更广泛地使用flex,否则您也可以删除display: flex;align-items,并且该列表仍然会在页面中居中并从第一个清单项目。

旧答案

选项1

#background {
  display: flex;
  align-items: flext-start;
  height: 100%;
}

选项2

#background {
  height: 100%;
}

更新答案

您可以使用CSS表格。

html, body {
  height: 100%;
  margin: 0px;
}
#background {
  display: table;
  height: 100%;
  margin: 0 auto;
  width: 200px;
}
#box {
  display: table-cell;
  vertical-align: top;
  background-color: yellow;
}
<div id="background">
    <ol id="box">
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
        <li>asdf asdf asdf</li>
    </ol>
</div>

演示JSFiddle

答案 1 :(得分:0)

只需省略对齐项目,您就不需要它来获得所需的外观:

#background {
  display: flex;
  // align-items: center;
  height: 100%;
}

答案 2 :(得分:-1)

您也可以在盒子类上使用margin-top:50%,您可以根据需要更改值