首页 文章

使用文本溢出时空格的位置:省略号;

提问于
浏览
3

我有一个移动网站的顶级栏,看起来像这样:
enter image description here

用户可以通过单击他/她的姓名来打开个人菜单 . 当这个人的名字很长(蓝色条)我想用 text-overflow: ellipsis 来缩短它 .

我得到了它(看起来像蓝色条)但现在如果我有一个简短的名称,箭头图标显示在右边(红色条) . 我想保留名称旁边的箭头和箭头右侧的剩余空格,如绿色栏中所示 .

我不想为任何元素(可能是按钮除外)设置宽度或最大宽度,因为我希望它在不同的移动设备上工作,因此可用的宽度是未知的 .

有没有办法用HTML和CSS实现这一目标?到目前为止我做了什么:

HTML

<button>Log off</button>
<div id="menu">
    <span id="icon">+</span>
    <span id="name">John Withthelonglastname</span>
</div>

CSS

#name {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

#icon { float:right;}
button { float: right;}

小提琴:http://jsfiddle.net/webwolfe/L07t0zk7/

3 回答

  • 1

    使用Flex可以使用 HTMLCSS 轻松实现此目的:

    .menu {
      width: 200px;
      padding: 2px;
      color: white;
      display: flex;
    }
    .blue {
      background: blue;
    }
    .red {
      background: red;
    }
    .name {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .icon {
      padding-left: 5px;
      padding-right: 5px;
      flex: 1 1 auto;
    }
    button {
      min-width: 70px;
    }
    
    <div class="menu blue">
      <span class="name">John Withthelonglastname</span>
      <span class="icon">+</span>
      <button>Log off</button>
    </div>
    
    <br>
    
    
    <div class="menu red">
      <span class="name">John Doe </span>
      <span class="icon">+</span> 
      <button>Log off</button>
    </div>
    

    记下FlexyBoxes作为玩家设置的小提琴手 .

    P.S:最好将类而不是ID用于通用元素

  • 1

    你可以使用一个甜蜜的 :before pseudoSelector而不是icon span

    #name:before
    {
    content:'+';
    z-index:999;
    display:inline-block;
    float:right
    }
    

    fiddle

  • 1

    您可以使用内容在名称后面的图标中添加内容 .

    #name {
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    #name:after{
        content: ' +';
        position: absolute;
    }
    

相关问题