【问题标题】:CSS left float with variable content and windows widthCSS左浮动内容和窗口宽度可变
【发布时间】:2017-12-02 19:08:32
【问题描述】:

我有一个可变的窗口大小和一个带有 3 个浮动块的标题。 第一个以固定宽度向右浮动,第二个以固定宽度向左浮动。最后一个 (varleft) 向左浮动,内容长度可变。

<div id="header">
  <div id="right">test</div>
  <div id="left">test</div>
  <div id="varleft">very long text very long text very long text very long text very long text very long text very long text very long text very long text </div>
</div>

我想防止第三个块在其宽度增加时低于其他块,此外,我想给它第二行用于长内容,然后用省略号截断字符串。

这些块是 bootstrap nav-header 块,所以我不能使用其他的,只能使用浮动来移动它们。

这是一个增长文本的文本示例: https://jsfiddle.net/mjq2tum0/

这是我希望的结果(固定宽度和单行省略号除外): https://jsfiddle.net/o90sm39L/

【问题讨论】:

  • 您的标题是否有背景色(不是图像)?如果是的话,我可能有一个解决方案。

标签: html css css-float


【解决方案1】:

我想防止第三个块在其宽度增加时低于其他块,此外,我想给它第二行用于长内容,然后用省略号截断字符串。

这里是解决方案。 请注意,只有当您使用纯色背景时,它才会起作用。

代码不仅仅是受到this awesome article的启发

如果这对你来说不是问题:

1. 我觉得box-sizing: border-box; 更实用:

#header > * {
  box-sizing: border-box;
}

2. 更改 div 的宽度 varleft

  width: calc(100% - 300px); // 100% minus the width of #right and #left

现在,您的 div varleft 不会进入其他块

3.varleft添加位置和溢出:

  overflow: hidden;
  position: relative;

4. 使用伪元素创建省略号...,并创建一个在不需要时隐藏... 的div

#varleft:before {
  content: '...';
  position: absolute;
  right: 0;
  bottom: 0;
}
#varleft:after {
  content: '';
  position: absolute;
  right: 0;
  width: 1em;
  height: 40px;
  background: white;
}

这是一个 sn-p:

$(function(){
  var ranchr = "A BCDE FGHI JKLMN OPQRS TUVWX YZabcd efghijklm nopqr stuvwx yz0123 456789";
	setInterval(function(){
    if($("#varleft").text().length>100)
        $("#varleft").text("");
  	$("#varleft").append(ranchr.charAt(Math.floor(Math.random() * ranchr.length)));
  },100);
});
#header{
  border: 1px solid #000;
  height: 42px;
  width: 100%;
  background: white;
}
#header > * {
  box-sizing: border-box;
}
#right{
  border: 1px solid #f00;
  float: right;
  width: 150px;
  height: 40px;
}
#left{
  border: 1px solid #0f0;
  float: left;
  width: 150px;
  height: 40px;
}
#varleft{
  border: 1px solid #00f;
  float: left;
  width: calc(100% - 300px);
  height: 40px;
  overflow: hidden;
  position: relative;
}

#varleft:before {
  content: '...';
  position: absolute;
  right: 0;
  bottom: 0;
}
#varleft:after {
  content: '';
  position: absolute;
  right: 0;
  width: 1em;
  height: 40px;
  background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
<div id="right">test</div>
<div id="left">test</div>
<div id="varleft"></div>
</div>

【讨论】:

    【解决方案2】:

    只需添加您的 css:

    #varleft {
       max-width: calc(100% - 306px);
    }
    

    【讨论】:

    • 你如何回应这个请求moreover, I want to give it a second line for long content, and then truncate string with ellipsis.
    • 您可以在 -> hackingui.com/front-end/… 阅读有关它的信息
    猜你喜欢
    • 2012-04-20
    • 2011-07-31
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2011-08-07
    相关资源
    最近更新 更多