html - 为动态包含的文本设置 div 百分比宽度的纯 css 解决方案

标签 html css

我想用 javascript 实现的目标非常简单,但如果可能,我需要一个纯 css 解决方案。

我有一个 438px X 348px 的 div。我正在这个 div 中生成一个动态列表。列表元素的高度均为 30px,并设置为 list-inline 和 float-left。我已将 li 宽度设置为 (33% - padding) 并将文本溢出设置为省略号。因此列表显示为 3 个统一列,当文本长于 li 元素的宽度时,它会被截断并在末尾显示“...”。现在我希望 li 元素根据包含的文本自动具有 33.3% 或 66.6% 或 100%。有没有纯 css 的解决方案?

这是我试过的javascript代码。

var listWidth = 432;
var oneColWidth = (33.3 * listWidth / 100) - 25;
var twoColWidth = (66.6 * listWidth / 100) - 25;
var threeColWidth = (99.9 * listWidth / 100) - 25;

$('#value_list_' + optionID + ' li').each(function() {
    var listItemWidth = $(this).find('div').width();

    if(listItemWidth < oneColWidth) {
        $(this).width(oneColWidth);
    }
    else if(listItemWidth < twoColWidth) {
        $(this).width(twoColWidth);
    }
    else {
        $(this).width(threeColWidth);
    }
});

它并没有完全按照我的意愿工作,但我需要一些类似的逻辑。这是我使用此代码取得的成果的屏幕截图。

enter image description here

最佳答案

我已经使用了 flex 并尝试了以下方法:您可以通过此了解 flex Flex link

这里的默认布局是 3 列,但如果有溢出,flex 会将下一个元素插入下一行...

.parent {
  width: 438px;
  height: 348px;
}

ul {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  padding-left: 0;
}

li {
  list-style: none;
  display: inline-block;
  min-width: calc(100% / 3);
  height: 30px;
}
<div class="parent">
  <ul>
    <li>content 1</li>
    <li>content 2 with extra characters</li>
    <li>content 3</li>
    <li>content 4</li>
    <li>content 5</li>
  </ul>
</div>

关于html - 为动态包含的文本设置 div 百分比宽度的纯 css 解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51490998/

相关文章:

java - 如何在我的 Web 应用程序中拥有文本区域?

javascript - 如何将 CSS 媒体查询的结果传递给 JS?

html - css 元素的定位不是我期望的位置

css - vuejs底部的偏移量+仅在移动设备上的vuetify应用程序

javascript - 在Javascript中计算二次曲线上任意点的切线斜率

javascript - onclick JS在ie8/9下不执行的问题

html - 创建一个免费的选择图像 map

css - div 中的文本自动移至底部

html - 如果特定子项仅存在 CSS,如何显示隐藏元素

html - 垂直对齐元素集