如何在调整浏览器窗口大小时保持文本在div中显示

4
所以我有一个简单的div,里面有一个带有一些文本的p标签。我希望文本保持在div内部,目前情况还不错,但是当我水平调整浏览器窗口大小时,div内的文本会从底部流出。

#textbox {
  position: absolute;
  left: 180px;
  top: 420px;
  height: 250px;
  width: 20%;
  background-color: white;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}

#text {
  text-align: center;
  font-family: 'Roboto', sans-serif;
  font-style: italic;
  font-size: 20px;
  word-wrap: break-word;
}
<div id="textbox">
  <p id="text">Here is some example text that is about the same amount as I really have here, but I don't want to reveal what.</p>
</div>

根据类似问题的答案,我需要添加word-wrap: break-word;,而我已经添加了。 如果有帮助的话,文本不会从左侧或右侧流出,而是从底部流出。
所以我的问题是,当我移动浏览器窗口时,我该怎么做才能让文本保持在div内部?

你尝试过 white-space: normal; 这个属性吗? - Barrosy
@Barrosy 是的,我试过了。它没起作用。 - Gyrgam
2
@Gyrgam,如果你不想让文本溢出,请不要给你的盒子一个固定和一个响应式的尺寸 - 要么两者都固定,要么两者都是流体的(例如,如果你要有一个响应式宽度,请删除高度)。 - Pete
@Pete 噢,我不知道。那就是我做错了的地方。谢谢,但因为我在这里还是新手,不知道如何将评论设置为解决方案。 - Gyrgam
@Gyrgam 你不能将评论标记为答案 :) 我会标记下面的min-height - 基本上是同样的东西。 - Pete
显示剩余4条评论
2个回答

3

只需将height: 250px替换为min-height: 250px;

#textbox {
  position: absolute;
  left: 180px;
  top: 420px;
  min-height: 250px;
  width: 20%;
  background-color: white;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}

#text {
  text-align: center;
  font-family: 'Roboto', sans-serif;
  font-style: italic;
  font-size: 20px;
  word-wrap: break-word;
}
<div id="textbox">
  <p id="text">Here is some example text that is about the same amount as I really have here, but I don't want to reveal what.</p>
</div>


为什么你要移除高度,如果你会使用以下代码:left: calc(50% - 10%); top: calc(50% - 125px); - Praveen Kumar Tripathi
我只把高度改成了最小高度,其余的代码是原作者的代码。你需要问他... - Itay Gal
如果你写left: calc(50% - 10%)和top: calc(50% - 125px,那么它将无法正常工作,而不改变任何高度。 - Praveen Kumar Tripathi
不确定您的意思。topleft只有帮助定位元素的作用,它们不会改变高度。您可以在问题下方发表评论,并询问提问者为什么要以这种方式定位他的元素。 - Itay Gal

1

通过简单更改样式,您可以将文本保留在内部。

在线演示:https://jsfiddle.net/y5sjdtoq/

尝试使用以下样式代码:

    #textbox {
        left: 180px;
        top: 420px;
        height: auto;
        padding: 20px;
        display: inline-block;
        width: 240px;
        background-color: white;
        box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
    }

    #text {
      text-align: center;
      font-family: 'Roboto', sans-serif;
      font-style: italic;
      font-size: 20px;
      word-wrap: break-word;
    }

2
这是一个不错的解决方案,我很感激,但我更喜欢已经被接受的那个。 - Gyrgam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接