标题:
如何用CSS实现多行文本的省略号显示(3)
[打印本页]
作者:
yuyang911220
时间:
2017-4-23 19:56
标题:
如何用CSS实现多行文本的省略号显示(3)
4th 削窄prop元素
目前,最左侧的prop元素的作用在于让realend元素在文本溢出时处在其正下方,在前几节的示例代码中为了直观的演示,设置prop元素的宽度为100px,那么现在为了更好的模拟实际的效果,我们缩小逐渐缩小prop元素的宽度。
<div class="wrap">
<div class="prop">1.prop<br>float:right</div>
<div class="main">2.main<br>float:left<br>Fairly short text</div>
<div class="realend">
3.realend<br>position:relative</div>
</div>
.prop {
float: left;
width: 5px;
height: 200px;
background: #F0F; }
.main {
float: right;
width: 300px;
margin-left: -5px;
background: #AFF; }
.realend {
float: right;
position: relative;
top: -50px;
left: 300px;
width: 100px;
margin-left: -100px;
padding-right: 5px;
background: #FAA; font-size: 14px; }
针对prop元素,缩小宽度为5px,其余属性不变;
针对main元素,设置margin-left:5px,让main元素左移5px,这样main元素在宽度上就完全占满了父元素;
对于realend元素,top、left和width的值不变。而设置margin-left: -100px、padding-right: 5px则是为了让realend元素的盒模型的最终宽度计算为5px。
BoxWidth = ChildMarginLeft + ChildBorderLeftWidth + ChildPaddingLeft + ChildWidth + ChildPaddingLeft + ChildBorderRightWidth + ChildMarginRightWidth;
具体可参考我之前的文章负margin的原理以及应用一文。
由于CSS规范规定padding的值不可以为负数,因此只有设置margind-left为负值,且等于其宽度。这样做的最终目的就是保证realend元素处在prop元素的下方,保证在文本溢出的情况下定位准确性:
5th 继续优化:流式布局+伪元素
目前,realend元素的相关属性仍采用px度量,为了更好的扩展性,可以改用%替代。
同时,prop元素和realend元素可以采用伪元素来实现,减少额外标签的使用。
<div class="ellipsis">
<div>2.main<br>float:left<br>Fairly short text
</div>
</div>
/*相当于之前的prop元素*/
.ellipsis:before {
content: "";
float: left;
width: 5px; height: 200px;
background: #F0F; }
/*相当于之前的main元素*/
.ellipsis > *:first-child {
float: right;
width: 100%;
margin-left: -5px;
background: #AFF; }
/*相当于之前的realend元素*/
.ellipsis:after {
content: "realend";
float: right; position: relative;
top: -25px; left: 100%;
width: 100px; margin-left: -100px;
padding-right: 5px;
background: #FAA; font-size: 14px; }
效果图和上节一样。
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/)
Powered by Discuz! 7.0.0