Flexbox align-items 溢出文本在顶部被切断 [英] Flexbox align-items overflow text get cuts off at top

查看:23
本文介绍了Flexbox align-items 溢出文本在顶部被切断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况,当文本不再适合容器时,它会在顶部被截断.我能做些什么来解决这个问题?如果文本比容器小,我仍然希望文本居中,并且我无法更改容器大小.

div {显示:弹性;对齐项目:居中;宽度:100px;高度:50px;溢出:自动;断字:断字;}

sdjhfkahsdkjfadsfhk jaskjfsj fsldflkasjklsjflakj flksjfakljflksjflkasfjklasjflfd

解决方案

这里的问题是由于使用align-items(或justify-content) 将 flex 行项目居中,按照设计,它会在其顶部/底部(或左侧/右侧)溢出.

为了解决这个问题,引入了一个新的关键字safe,不过目前支持的浏览器还不多.

<小时>

另一种选择是使用自动边距,尽管使用给定的标记你不能,因为文本没有内部包装器(好吧,它有一个匿名的,尽管那些我们不能用CSS 选择器).

因此,通过添加内部包装器(摆弄包装器),您可以使用自动边距,并且得到了很好的解释这里:

<小时>

但有时我们只是无法更改标记,当,这里有一个小技巧,使用伪元素,并在它们上使用自动边距.

要使文本垂直居中,我们还需要将 flex 方向设为 column,以便伪代码呈现在上方/下方.

堆栈片段

div {显示:弹性;弹性方向:列;/*  添加  */宽度:100px;高度:50px;溢出:自动;断字:断字;边框:1px纯灰色;}div::before, div::after {内容: '';}div::before {边距顶部:自动;/*  添加  */}div::after {底边距:自动;/*  添加  */}

sdjhfkahsdkjfadsfhk jaskjfsj fsldflkasjklsjflakj flksjfakljflksjflkasfjklasjflfd

<div>sdjhf

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>

解决方案

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>

这篇关于Flexbox align-items 溢出文本在顶部被切断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆