简体   繁体   中英

How to randomise word spacing in a paragraph?

I'm trying to make a panel of words that are distributed unevenly.

Here's a very basic sample image:

随机字面板

Using text-align and word-spacing I have come close..

 body { width: 500px; margin: 50px auto 0; } p { background: lightgrey; padding: 2em; font-size: 2em; font-family: sans-serif; word-spacing: 2em; text-align: center; } p span { font-size: 1em; color: white; } 
 <p>one two three four five six seven eight nine ten eleven twelve thirteen fourteen <span>fifteen</span> sixteen seventeen eighteen nineteen twenty</p> 

However I'd like to randomise the spacing between words. Is this possible with CSS? I'm open to changing the HTML, but these panels are dynamically generated and could have any number of words.

Any suggestions?

Codepen for those who prefer

Use JS to generate random position on page. I made simply random position, you can use more complex algorithm

 $(document).ready(function() { var texts = $('p').text().split(' '); $('p').text(''); $.each(texts, function() { $('p').append( $('<span>', { text: this, "class": this == 'fifteen' ? 'active' : '', css: { left: Math.floor(Math.random() * $('p').width()), top: Math.floor(Math.random() * $('p').height()), fontSize: Math.floor(Math.random() * 20) + 10 } }) ); }); }); 
 p { width: 100%; height: 400px; position: relative; } p span { position: absolute; font-size: 18px; color: #555; } p span.active { color: #00aaff; font-weight: bold; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty</p> 

One option is to use white-space: pre-wrap on your element and js to generate random number of white-spaces between each word.

 var min = 1; var max = 15; var newText = $('p').html().replace(/\\s/g, function() { return " ".repeat(parseInt(Math.random() * (max - min) + min)) }); $('p').html(newText) 
 body { width: 500px; margin: 50px auto 0; } p { background: lightgrey; padding: 2em; font-size: 1.5em; font-family: sans-serif; text-align: center; white-space: pre-wrap; } p span { font-size: 1em; color: white; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>one two three four five six seven eight nine ten eleven twelve thirteen fourteen <span>fifteen</span> sixteen seventeen eighteen nineteen twenty</p> 

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