How can you use flexbox to vertically center text in a fixed-height div without overflowing above?

后端 未结 3 955
谎友^
谎友^ 2021-01-14 04:45

The first line of text in the third .box is raised above the top of the div and cut off. I would like it to appear the same as the second box (well actually ide

3条回答
  •  余生分开走
    2021-01-14 05:28

    You can center the single line of text by simply wrapping it in a and giving it a width.

    one line of text
    div.box > span { width: 100%; }

    OR, you can apply the justify-content property to the flex container:

    .box {
        display: flex;
        align-items: center; /* center vertically */
        justify-content: center; /* center horizontally */
        height: 40px;
        font-size: 16px;
        width: 150px;
        border: 1px solid black;
        margin-bottom: 40px;
        text-align: center;
        overflow-y: hidden;
    }
    

    In terms of adding ellipsis ("...") to overflow text, yes it's possible, but it's tricky with multi-line text.

    CSS has a text-overflow property that takes several values, including ellipsis. Unfortunately, ellipsis only works on single-line text.

    CSS doesn't provide a standard way to apply ellipsis to multi-line text. There are various workarounds, but they can be hit and miss depending on the method and the situation. See my answer here for more details: Applying Ellipsis to Multiline Text

提交回复
热议问题