Flexbox align-items overflow text get cuts off at top [duplicate]

有些话、适合烂在心里 提交于 2019-12-02 02:40:41

The problem here is caused by the fact that when using align-items (or justify-content) to center a flex row item, it will, by design, overflow at its top/bottom (or left/right).

To solve that a new keyword, safe, is introduced, though not many browsers support it yet.


The other option is to use auto margin's, though with the given markup you can't, as the text doesn't have an inner wrapper (well, it has an anonymous one, though those we can't target with a CSS selector).

So by adding an inner wrapper (fiddle with wrapper) you can use auto margin's, and is well explained here:


But sometimes we just can't change the markup, and when, here is a little trick, using the pseudo elements, and use auto margin's on them.

To vertical center the text we also need the flex direction to be column so the pseudo is rendered above/below.

Stack snippet

div {
  display: flex;
  flex-direction: column;         /*  added  */
  width: 100px;
  height: 50px;
  overflow: auto;
  word-break: break-word;
  border: 1px solid gray;
}

div::before, div::after {
  content: '';
}
div::before {
  margin-top: auto;               /*  added  */
}
div::after {
  margin-bottom: auto;            /*  added  */
}
<div>
  sdjhfkahsdkjfadsfhk jaskjfsj fsldflkasjklsjflakj flksjfakljflksjflkasfjklasjflfd
</div>

<div>
  sdjhf
</div>

If you wrap the text into another tag, and set margin: auto 0; it seems to be working well.

div {
  display: flex;
  width: 100px;
  height: 50px;
  overflow: auto;
  word-break: break-word;
  background: pink;
  margin-bottom: 20px;
}

span {
  margin: auto 0;
}
<div>
  <span>sdjhfkahsdkjfadsfhk jaskjfsj fsldflkasjklsjflakj flksjfakljflksjflkasfjklasjflfd</span>
</div>

<div>
  <span>sdjhfkah</span>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!