简体   繁体   中英

How do I make the text in the next line to be centered and not aligned to the left?

I have a div that has the following CSS:

 .div_stuff {
 width: 830px;
 margin: 20px auto;
 font-size:22px;
 }

How do I prevent the text that goes to the next line to not align left right under the text above but simply become centered on the next line?

Although I'm not sure if I understood what you want to achieve and I can't find a use case for this... Changing the alignment from the second line on would be possible by adding some span tags with javascript/jQuery ( DEMO ):

$(function() {
    var box = $('.div_stuff');
    var text = box.text();

    var words = text.split(' ');
    box.text(words[0]);
    var height = box.height();
    var chars = 0;
    for(var i = 1; i < words.length; i++){
        box.text(box.text() + ' ' + words[i]);
        chars += words[i-1].length + 1;
        if(box.height() > height){
            height = box.height();      
            box.html('<span class="first-line">' + text.substring(0,chars) + '</span><span class="following-lines">' + text.substring(chars+1, text.length)+'</span>');
            break;
        }
    }
});

And set a different alignment to them:

span {
    display: block;
}

.first-line {
    text-align: left;
}

.following-lines {
    text-align: center;
}

I've used that answer for determining auto line breaks.

Add text-align: center to center the text inside. You are centering the div position only.

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