How can I wrap or break long text/word in a fixed width span?

前端 未结 7 1965
长发绾君心
长发绾君心 2020-12-22 22:27

I want to create a span with a fixed width that when I type any thing in the span like lgasdfjksdajgdsglkgsadfasdfadfasdfadsfasdfasddkgjk

相关标签:
7条回答
  • 2020-12-22 22:45

    Try this

    span {
        display: block;
        width: 150px;
    }
    
    0 讨论(0)
  • 2020-12-22 22:46

    By default a span is an inline element... so that's not the default behavior.

    You can make the span behave that way by adding display: block; to your CSS.

    span {
        display: block;
        width: 100px;
    }
    
    0 讨论(0)
  • 2020-12-22 22:49

    You can use the CSS property word-wrap:break-word;, which will break words if they are too long for your span width.

    span { 
        display:block;
        width:150px;
        word-wrap:break-word;
    }
    <span>VeryLongLongLongLongLongLongLongLongLongLongLongLongExample</span>

    0 讨论(0)
  • 2020-12-22 22:56

    Like this

    DEMO

      li span{
        display:block;
        width:50px;
        word-break:break-all;
    }
    
    0 讨论(0)
  • 2020-12-22 22:58

    Just to extend the pratical scope of the question and as an appendix to the given answers: Sometimes one might find it necessary to specify the selectors a little bit more.

    By defining the the full span as display:inline-block you might have a hard time displaying images.

    Therefore I prefer to define a span like so:

    span {
      display:block;
      width:150px;
      word-wrap:break-word;      
    }
    p span, a span,
    h1 span, h2 span, h3 span, h4 span, h5 span {
      display:inline-block;
    }
    img{
      display:block;
    }
    
    0 讨论(0)
  • 2020-12-22 23:01

    In my case, display: block was breaking the design as intended.

    The max-width property just saved me.

    and for styling, you can use text-overflow: ellipsis as well.

    my code was

    max-width: 255px
    overflow:hidden
    
    0 讨论(0)
提交回复
热议问题