Search code examples
csscss-grid

How do I set text-overflow to ellipsis in CSS grid layout?


I have a grid layout like the one in header below. There is a text in the div whose width is 1fr. I want the text inside that div to be truncated when it is too long. Adding text-overflow as ellpsis is not working. Any idea how to do it?

It has to be grid and there is no way I can change that.

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  text-overflow: ellipsis;
}
<div class="container">
  <header>
    <div>Left</div>
    <div class="long">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
    <div>Right</div>
  </header>
  <content>
  </content>
</div>


Solution

  • change .long css to below

    .long {
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
    }
    

    the reason why you need to add white-space and overflow is below:

    1. you need white-space: nowrap to tell browsers to not wrap when text length exceed containing block width, white-space properties default value is normal, which indicates it can wrap, so it won't exist the situation where text overflow;
    2. overflow default value is visible, when text exceeds containing block, it just display, so there is no need to overflow text to display, only if you set overflow to hidden. Then, when text can not fully displayed, it will use text-overflow property.