CSS: Left, Center, & Right Align Text on Same Line

前端 未结 8 906
借酒劲吻你
借酒劲吻你 2020-12-04 18:03

I need to left, center, & right align text on the same line. I have the following text:

  • Left Align: 1/10
  • Center: 02:27
  • R
8条回答
  •  长情又很酷
    2020-12-04 18:22

    If you are also looking to top, middle, and bottom align text across the same line then one can expand on @Thameem's answer to get an even more complete positioning solution:

    top left top center top right
    middle left middle center middle right
    bottom left bottom center bottom right

    With HTML custom elements and a bit of CSS you can optionally make it a bit more readable:

    
        
            top lefttop centretop right
        
        
            middle leftmiddle centremiddle right
        
        
            bottom leftbottom centrebottom right
        
    
    

    And the corresponding CSS:

    position {
        display: table;
        table-layout: fixed;
        height: 100%;
        width: 100%;
    }
    
    top {
        display: table-row;
    }
    top * {
        vertical-align: top;
    }
    
    middle {
        display: table-row;
    }
    middle * {
        vertical-align: middle;
    }
    
    bottom {
        display: table-row;
    }
    bottom * {
        vertical-align: bottom;
    }
    
    left {
        display: table-cell;
        text-align: left;
    }
    
    centre {
        display: table-cell;
        text-align: center;
    }
    
    right {
        display: table-cell;
        text-align: right;
    }
    

    Please note the British spelling of "centre" instead of "center" in some places. I am not British but this was done to avoid conflicting with the existing HTML "center" element and its built-in styles. If you happen to know the magic combination of styles to override the "center" element I would be interested to hear.

    You can also use this to do fewer positions:

    
        
            centre
        
    
    

    But be careful to use the same set of "columns" (left, center, right) between "rows" (top, middle, bottom) since it is technically still a table underneath.

    I realize I probably committed a few programming sins with this example:

    1. mixing content and layout
    2. not namespacing my custom elements (which could involve naming conflicts if the names I chose happen to be used by a library or the HTML/XML spec)
    3. not using the more modern flex layout
    4. etc.

    Please forgive me.

    I have found it difficult to achieve similar layout using other solutions. I hope this helps other people struggling with similar requirements.

提交回复
热议问题