Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 323
A. L Avatar asked Feb 20 '18 00:02

A. L


2 Answers

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>
like image 199
Asons Avatar answered Sep 26 '22 11:09

Asons


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>
like image 37
Stickers Avatar answered Sep 23 '22 11:09

Stickers