我如何使内联块保持在单行但仍适合可用宽度?

时间:2017-04-25 18:59:21

标签: html css

我有以下演示代码演示我的问题。我想通过CSS在标题旁边添加一些装饰并且有这个问题。如果标题足够短,它可以按预期工作,但如果标题更长,那么当文本环绕但不足以进入div.base时。

如何将第二个样本看作下面的第三个(假)样本? enter image description here

为了清楚起见,我希望div内容显示为“inline”,只允许中间div进行自动换行,div内容应保持在容器宽度内,而不会在div之间添加额外的空格。

<html>
    <style>
        .base { font-size:32pt; text-align:center; border:solid; display: block; white-space:nowrap; width:400px;}
        .base span, .base::before, .base::after { display: inline-block; border:solid; white-space:normal;}
        .base::before { content: "\00a0-\00a0"; }
        .base::after { content: "\00a0-\00a0"; }
    </style>
    <body>
        <div class="base">
            <span>Short text</span>
        </div>
        <div class="base">
            <span>Testing some longer text</span>
        </div>
        <div class="base">
            <span>Fake some <br>longer text</span>
        </div>
    </body>
</html>

2 个答案:

答案 0 :(得分:0)

两种方法,第二种方式更好(flex),但依赖于浏览器支持:

1。)您可以在该范围内使用具有百分比或(更好)max-width值的calc

.base {
  font-size: 32pt;
  text-align: center;
  border: solid;
  display: block;
  white-space: nowrap;
  width: 400px;
}

.base span,
.base::before,
.base::after {
  display: inline-block;
  border: solid;
  white-space: normal;
}

.base::before {
  content: "\00a0-\00a0";
}

.base::after {
  content: "\00a0-\00a0";
}
.x2 span {
  max-width: calc(100% - 112px);
}
<div class="base x1">
  <span>Short text</span>
</div>
<div class="base x2">
  <span>Testing some longer text</span>
</div>
<div class="base x3">
  <span>Fake some <br>longer text</span>
</div>

2.。)这是使用flexbox的第二个解决方案:

.base {
  font-size: 32pt;
  text-align: center;
  border: solid;
  display: block;
  white-space: nowrap;
  width: 400px;
  display: flex;
  justify-content: center;
}

base span {
}

.base span,
.base::before,
.base::after {
  display: inline-block;
  border: solid;
  white-space: normal;
}

.base::before {
  content: "\00a0-\00a0";
  margin-right: 10px;
}

.base::after {
  content: "\00a0-\00a0";
  margin-left: 10px;
}
<div class="base x1">
  <span>Short text</span>
</div>
<div class="base x2">
  <span>Testing some longer text</span>
</div>
<div class="base x3">
  <span>Fake some <br>longer text</span>
</div>

答案 1 :(得分:-1)

简单,相应地将max-width提供给span元素。

.base {
  font-size: 32pt;
  text-align: center;
  border: solid;
  display: block;
  white-space: nowrap;
  width: 400px;
}

.base span {
  max-width: 60%;
}
.base::before {
  max-width: 20%;
}
.base::after {
  max-width: 20%;
}

.base span,
.base::before,
.base::after {
  display: inline-block;
  border: solid;
  white-space: normal;
}

.base::before {
  content: "\00a0-\00a0";
}

.base::after {
  content: "\00a0-\00a0";
}
<div class="base">
            <span>Short text</span>
        </div>
        <div class="base">
            <span>Testing some longer text</span>
        </div>
        <div class="base">
            <span>Fake some <br>longer text</span>
        </div>