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

独自空忆成欢 提交于 2019-12-04 03:38:14

问题


I have the following situation, the text get cuts off at the top when it not longer fits inside the container. What can I do to fix that? I'd still like the text to be centered if it's smaller than the container, and I can't change the container size.

div {
  display: flex;
  align-items: center;
  width: 100px;
  height: 50px;
  overflow: auto;
  word-break: break-word;
}
<div>
  sdjhfkahsdkjfadsfhk jaskjfsj fsldflkasjklsjflakj flksjfakljflksjflkasfjklasjflfd
</div>

回答1:


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.

  • How to use safe center with flexbox?

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:

  • Can't scroll to top of flex item that is overflowing container

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>



回答2:


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>


来源:https://stackoverflow.com/questions/48876120/flexbox-align-items-overflow-text-get-cuts-off-at-top

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