简体   繁体   中英

CSS3 ellipsis, centered text and responsive design

There's a billion of tutorials, but none have worked for me unfortunately. I need some artistnames to be in the header, centered, but with a css ellipsis, so very long names gets the "..." and will be truncated.

You can see the design here: http://www.cphrecmedia.dk/musikdk/mobile/artistchannel.php Remember to resize your browser window.

Its meant for mobiles, so I cannot have any fixed withs and it should work with all kinds of mobile screensizes. I can make the ellipsis work, but then the text is no longer centered. Any clue on how to do this best? I would really like to avoid any javascript as performance is highly important.

You need to update the rules for h1 with overflow & text-overflow .

.header h1, .headerwhite h1 {
    font-size: 15px;
    line-height: 49px;
    text-overflow: ellipsis;/* generates dots if text on one single line and truncated */
    overflow: hidden;/* triggers text-oveflow and mids floatting elements */
    white-space: nowrap;/* keep text on a single line to trigger text-overflow; */
    display: block;/* reset to basic behavior of h1 , else inline-block drops down if not enough room */
}

basicly same answer as dartanian300 :)

You may control the max-width of h1 too and add a margin:auto; : demo

UPDATE

Using display: inline-block simply removes the h1 altogether on smaller screens. You should avoid this.

Also, technically, the text is still centered. It takes into account the ellipsis when centering the text.

ORIGINAL ANSWER

In order for the ellipsis styling to work, you've got to set a few things on the element with the text:

  • display: block;
  • text-overflow: ellipsis;
  • overflow: hidden;
  • white-space: nowrap;

display: block ensures that the box you're trying to generate ellipsis on is shown as a block. If it's not, it won't know where the bounding box is.

text-overflow: ellipsis obviously should generate the ellipsis.

overflow: hidden for some reason, browsers won't generate the ellipsis unless you have this. I believe it has to do with the fact that the text will just flow outside the box with it.

white-space: nowrap this prevents your text from wrapping onto multiple lines. That way, you have one line with ellipsis at the end.

That work?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM