首页 > 解决方案 > 防止文本包装器在文本溢出到下一行后跨越其父级的整个宽度

问题描述

在响应式设计中,当我缩小宽度时,文本会溢出到下一行,并且文本包装器现在占用其父级的整个宽度。有没有办法防止这种情况?所以它看起来像红色的容器?

我可以在容器上添加填充(我会,比如 1em),但这仍然不是我想要的,因为它会使文本包装器始终保持相同的宽度(溢出后)。我宁愿让这些文本包装器根据其内容具有宽度。

这是 jsFiddle: https ://jsfiddle.net/derive/n2qk03wt/8/

这是测试代码:

*, *:before, *:after {
	box-sizing: border-box;
	-moz-box-sizing: border-box;
}

html,body {
  width: 100%;
  height: 600px;
  margin: 0;
  padding: 0;
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
}

div {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 30%; 
  height: 200px;
  margin-bottom: 1em;
}

.red {
  background: red;
}

.blue {
  width: 20%;
  backgroud-color: #064f7f;
}

span {
  padding: 1em;
  font-size: 25px;
  background: white;
  text-align: center;
}
<div class="red">
<span>some text here</span>
</div>

<div class="blue">
<span>some text here</span>
</div>

标签: htmlcss

解决方案


请在下面找到 css 代码。

    *, *:before, *:after {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
}

html,body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
}

div {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40%; 
  height: 200px;
  margin-bottom: 1em;
}

.red {
  background: red;
}

.blue {
  width: 30%;
  background: blue;
}

span {
  padding: 5px;
  font-size: 30px;
  background: white;
  text-align: center;
  width: 98%;
}

我希望这可以帮助你


推荐阅读