Search code examples
htmlcssellipsis

Position of whitespace while using text-overflow: ellipsis;


I have a top bar for a mobile website which looks like this: enter image description here

The user can open a personal menu by clicking his/her name. When the name of the person is very long (blue bar) I want to shorten it using text-overflow: ellipsis.

I got that to work (looks like the blue bar) but now if I have a short name the arrow icon is shown on the right (red bar). I want to keep the arrow next to the name and the remaining whitespace on the right of the arrow, as in the green bar.

I don't want to set a width or max-width to any of the elements (except maybe the button) because I want it to work on different mobile devices, therefore the available width is unknown.

Is there any way to achieve this with just HTML and CSS? What I have done so far:

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;}

Fiddle here: http://jsfiddle.net/webwolfe/L07t0zk7/


Solution

  • You can easily achieve this with HTML and CSS by using Flex:

    .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>

    Take note of FlexyBoxes as a fiddler to play with its settings.

    P.S: it is better to use classes instead of IDs for general purpose elements