html - 使文本适应容器的宽度

标签 html css

我正在尝试使一些 a 元素适应它们所在容器的总宽度。

这是我目前拥有的代码:http://codepen.io/anon/pen/FsgvI

HTML

<div class="box">
  <div class="title">
    <div class="something">
      <h3>
        <a href="#">This is foo</a>
        >
        <a href="#">and then bar</a>
        >
        <a href="#">and then test</a>
      </h3>
    </div>
  </div>
  <div class="content">
    asdijfg asoidf oasidf aosidf
  </div>
</div>

CSS

.box {
  border: 1px solid red;
  display: inline-block;
}

.content {
  border: 1px solid blue;
  width: 170px;
  height: 100px;
}

.title {
  height: 30px;
}

h3, h3 > a {
  text-overflow: ellipsis;
  overflow: hidden;
}

如何使文本适应 box 容器的宽度?我所说的“适应”是指保持当前字体大小并剪切(省略号)不适合内部的文本。

问候

编辑:

抱歉造成误会。我无法为 box 类设置宽度,因为我不知道它的宽度。我需要它的宽度与元素(content 框)一样多。

最佳答案

这可以通过对 CSS 进行一些更改来实现。

  • 制作 .title position: relative; 这将使 h3 位置相对于它
  • 制作h3 position: absolute; 将其从文档流中取出并赋予它width: 100%
  • white-space: nowrap; 添加到 h3 停止内容换行到新行
  • .content 中删除 width: 170px; 以使其占用尽可能多的空间

.box {
  border: 1px solid red;
  display: inline-block;
}

.content {
  border: 1px solid blue;
  height: 100px;
}

.title {
  position: relative;
  height: 50px;
  width: 100%;
}

h3 {
  position: absolute;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  width: 100%;
}
<div class="box">
  <div class="title">
    <div class="something">
      <h3>
        <a href="#">This is foo</a>
        >
        <a href="#">and then bar</a>
        >
        <a href="#">and then test</a>
      </h3>
    </div>
  </div>
  <div class="content">
    asdijfg asoidf oasidf aosidf
  </div>
</div>

代码笔: http://codepen.io/anon/pen/GgkJr

关于html - 使文本适应容器的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26515122/

相关文章:

javascript - 更新指令的范围并使用另一个指令进行观察

javascript - 大小之间的差异 javascript 转换 :scale(? .?)

javascript - HTML 切换菜单消失

javascript - 将 Canvas 放在 CSS 文本框的顶部

html - 主页宽度与主题中的其他页面宽度不同

html - 网站在 ie78 下不工作

javascript - 平滑上下滚动到多个 anchor

javascript - popbox.css 和 bootstrap.css 之间的名称冲突

javascript - 试图创建一个 jquery/javascript 函数来切换显示的 div,向后切换时出现故障

html - Bootstrap 导航栏固定在顶部时反复跳转