Search code examples
csscss-multicolumn-layout

CSS center columns of text


I have some song lyrics in a <div> with the following class:

.lyrics
{
    /* position */
    margin: 40px;

    /* text */
    font-size: 18px;
    text-align: center;
    column-width: 300px;
    column-gap: 0;
    column-fill: auto;
    height: 420px;
    max-height: 420px;
}

Width of the entire div is constrained to 1120px, and height to 520px.

If lyrics fill 3 columns, it looks fine. However, if lyrics fill 2 columns, space for a third column is left empty.

Is there a way to leave 3-column lyrics as they are, but to center 2-column lyrics, keeping column spacing the same, without resorting to slicing lyrics in javascript and processing the layout myself?

Examples

Correct behaviour with 3-columns: https://jsfiddle.net/udc9d1go/2/
Incorrect behaviour with 2-columns: https://jsfiddle.net/45f23o82/


Solution

  • I ended up writing some ES to increase left and right margins for the div in case text has a certain number of lines. This seems a fine work-around.

    calculateMarginForLyrics = function(lyrics)
    {
        // count <br /> tags and count </p> tags twice (except last one)
        var nLines = lyrics.match(/<br \/>/g || []).length + (lyrics.match(/<\/p>/g || []).length - 1) * 2;
    
        if (nLines <= 12) // fits in one column
            return 350;
        else if (nLines <= 24) // fits in two columns
            return 200;
    
        // fits in three columns
        return 40;
    }
    

    Result: JSFiddle