I am trying to detect focus on a child element of a contenteditable element, for the purposes of pure CSS styling. (I know I could detect this with JS, add an extra class and do it that way, but that is so long-winded.)
Basically, I have something along the lines of:
<div contenteditable="true">
Some text <span class="edit">that</span> goes here.
</div>
I tried CSS along the lines of:
.edit:focus {
color: #FF0000;
}
I want that span to change colour when the caret enters it, but apparently the focus is only applied to the div set to contenteditable, not to any child thereof. I have tried applying a second contenteditable to the span, but besides being a horribly sloppy approach, it doesn't work anyway.
Is there a solution to this?
Because of the limitation that elements within a contenteditable element can't generally receive focus, I suggest faking it by adding a class to your <span> element when the selection is contained within it, which you can do by monitoring the selection for changes (you'll have to use mouse and keyboard events and polling for thoroughness in Firefox until the selectionchange event is implemented in that browser).
var selectionContainer = null;
function updateSelectionContainer() {
var newSelectionContainer = null;
var sel;
if (window.getSelection && (sel = window.getSelection()).rangeCount) {
newSelectionContainer = sel.getRangeAt(0).commonAncestorContainer;
// Ensure we have an element rather than a text node
if (newSelectionContainer.nodeType != 1) {
newSelectionContainer = newSelectionContainer.parentNode;
}
}
if (newSelectionContainer != selectionContainer) {
if (selectionContainer) {
selectionContainer.className = selectionContainer.className.replace(/ ?containsSelection/, "");
}
if (newSelectionContainer) {
newSelectionContainer.className +=
(newSelectionContainer.className ? " containsSelection" : "containsSelection");
}
selectionContainer = newSelectionContainer;
}
}
if ("onselectionchange" in document) {
document.onselectionchange = updateSelectionContainer;
} else {
var el = document.getElementById("editor");
el.onmousedown = el.onmouseup = el.onkeydown = el.onkeyup = el.oninput = updateSelectionContainer;
window.setInterval(updateSelectionContainer, 100);
}
div {
font-size: 200%;
}
.edit.containsSelection {
color: red;
font-weight: bold;
}
<div contenteditable="true" id="editor">
Some text <span class="edit">that</span> goes here.
</div>
My understanding is that the type of elements that can receive focus (automatically) is limited.
See SO Question
One option is to add tabindex to the span.
body {
font-size: 3rem;
}
div[contenteditable=true] .edit:focus {
color: #FF0000;
}
<div contenteditable="true">Some text <span class="edit" tabindex="0">that</span> goes here.</div>
:focus > .edit { color: #cc0000; }
<div contenteditable="true">Some text <span class="edit">that</span> goes here.</div>
<div contenteditable="true">Some text that goes here.</div>
Just add this instead of :focus. Fiddle.
.edit {
color: #f00;
}
Related
This question already has answers here:
Is there a CSS parent selector?
(33 answers)
Closed last month.
So I am using a rust markdown parser and it renders header_ids by placing an <a> tag with an id inside the <h> tags.
So I am getting something like:
<h3>
"TEXT"
</h3>
So I want to color the text thats in the <h3> tag by target it by the id thats on the <a> tag. So not target the directly because then I would color all the <h3> tags.
I tried some different css selectors and what not to target it, but nothing worked. Not even sure if thats possible.
you can try something like that:
h3:has(> #test) {
color: red;
}
<h3>text</h3>
<h3>text <a id="test" href="#">text</a> text</h3>
Although you can achieve that with some CSS it's not the correct way to do it.
IDs should only be used for specific cases or not at all in my opinion. It's fine to use an ID for some Javascript selectors due to performance but for CSS seems like and over kill.
If you want to have the H3 having one color and the A tags inside it just do:
h3 {
color: black;
}
h3 > a {
color: red;
}
<h3>
This is a title
</h3>
<h3>
This is a title with some anchor
</h3>
If you want only that particular A tag of that H3 to change color, then use a class instead like so:
h3 {
color: black;
}
h3 > .anchor {
color: red;
}
<h3>
This is a title
</h3>
<h3>
This is a title with some anchor
</h3>
If you are using an ID in order to create an anchor link to that ID that's fine, but you should not use CSS selectors to attribute CSS Styles to something as trivial as an A tag.
If JavaScript isn't out of scope, you can query regularly for h3 a and then use the parentElement to assign the styling:
const linksWithH3 = document.querySelectorAll("h3 a");
for(let index = 0; index < linksWithH3.length; index++) {
const parentElement = linksWithH3[index].parentElement;
parentElement.style.color = "red";
}
<h3>
"TEXT"
</h3>
Or you can introduce a class:
const linksWithH3 = document.querySelectorAll("h3 a");
for(let index = 0; index < linksWithH3.length; index++) {
const parentElement = linksWithH3[index].parentElement;
parentElement.classList.add("h3-with-a");
}
.h3-with-a {
color: red;
}
<h3>
"TEXT"
</h3>
I have say 3 spans as below :
<span class = "testVar1" onClick = "testFunction(Var1)">
<span class = "testVar2" onClick = "testFunction(Var2)">
<span class = "testVar3" onClick = "testFunction(Var3)">
testFunction(var){
here I assign class "on" to the span which calls this function
}
If span with class testVar1 calls this then it becomes
<span class = "testVar1 on" onClick = "testFunction(Var1)"></span>
My Css is as below
.test .on {
some CSS
}
Is there a way in CSS where I can use a variable and apply css to those span which is clicked?
Like
.test[Var1 or Var2 or Var3] .on {
some CSS
}
I have achieved it by using multiple selectors manually like#
.testVar1 .on {
some CSS
}
.testVar2 .on {
some CSS
}
I have read the post Using regular expression in css? , it,s helpful but not answering my question.
In this post css is applied to all the element, but I want css to be applied only to the element which called the function.
and so on.
Any help or pointers would be appreciated!
Thanks!
You are making things too complicated. Just use the same CSS class on all of them, then add the click listener programmatically, not as an inline onlick listener:
document.querySelectorAll('span.test').forEach(
span =>
span.addEventListener('click', () => {
console.log(`you clicked ${span.innerText}`)
span.classList.toggle('on')
})
)
.test {
background: red;
color: white;
display: inline-block;
padding: 40px;
}
.test.on {
background: green;
}
<span class="test">foo</span>
<span class="test">bar</span>
<span class="test">baz</span>
If you insist on inline event listeners (you really shouldn't, it's widely considered bad practice), for this simple example it's probably even easier:
function foobar(span) {
console.log(`you clicked ${span.innerText}`)
span.classList.toggle('on')
}
.test {
background: red;
color: white;
display: inline-block;
padding: 40px;
}
.test.on {
background: green;
}
<span class="test" onclick="foobar(this)">foo</span>
<span class="test" onclick="foobar(this)">bar</span>
<span class="test" onclick="foobar(this)">baz</span>
You can use regex selector: span[class^='test'] which means select every span with class start with "test".
You can combine it with another class (.on) like that: span[class^='test'].on
As for inline code, you can do something like that:
const spans = document.querySelectorAll('span[class^="test"]'); // select all spans
for (var i=0; i < spans.length; i++) { // iterate them
spans[i].addEventListener('click',function() { // add event listener to them
this.classList.add('on'); // set class on click
});
}
span[class^='test'] {color: blue;}
span[class^='test'].on { color: red; }
<span class="testVar1">1</span>
<span class="testVar2">2</span>
<span class="testVar3">3</span>
Check this for selecting element with more then one class.
And this for regExp selector.
Enjoy code!
I'm trying to make a span background change colors when I focus on an input field. The HTML is as follows:
<div class='parentDiv'>
<span class='spanClass'>Some text</span>
<input class='inputClass' type='text' />
</div>
The closest I could come to something that does this is using the + adjacent sibling selector and doing something like this:
input:focus + span {
background-color: red;
}
But it doesn't quite work because span must come after input. Is there some way for me to make the span background change colors when I focus the input field?
Normally, you would need JS to do that. Here's an example using JS that keeps styling in your CSS:
(function() {
var spanEl = document.querySelector('.parentDiv > .spanClass');
var inputEl = document.querySelector('.parentDiv > .inputClass');
// Add "highlighted" class to "spanClass" element on focus event
inputEl.addEventListener('focus', function() {
spanEl.classList.add('highlighted');
});
// Remove "highlighted" class from "spanClass" element on blur event (un-focus)
inputEl.addEventListener('blur', function() {
spanEl.classList.remove('highlighted');
});
})();
.spanClass.highlighted {
background-color: red;
}
<div class="parentDiv">
<span class="spanClass">Some text</span>
<input class="inputClass" type="text" />
</div>
In your example, though, you could simply float the one element to the left and change the order in the HTML.
.parentDiv { overflow: hidden; }
.spanClass { float: left; }
.inputClass:focus + .spanClass {
background-color: red;
}
<div class="parentDiv">
<input class="inputClass" type="text" />
<span class="spanClass">Some text</span>
</div>
Something to note for the future, though:
The :has() "relational pseudo-class" seems to be in the works for "CSS4". You can also track it here: http://caniuse.com/#feat=css-has
This means that you will (hopefully) be able to do this eventually:
.spanClass:has(+ .inputClass) {
background-color: red;
}
Line 3 is a hidden <div> . I don't want that one to be taken from the odd/even css rule.
What is the best approach to get this to work?
.hidden {display:none;}
.box:not(.hidden):nth-child(odd) { background: orange; }
.box:not(.hidden):nth-child(even) { background: green; }
<div class="wrap">
<div class="box">1</div>
<div class="box">2</div>
<div class="box hidden">3</div>
<div class="box">4</div>
<div class="box">5</div>
<div class="box">6</div>
<div class="box">7</div>
</div>
http://jsfiddle.net/k0wzoweh/
Note: There can be multiple hidden elements.
:nth-child() pseudo-class looks through the children tree of the parent to match the valid child (odd, even, etc), therefore when you combine it with :not(.hidden) it won't filter the elements properly.
Alternatively, we could fake the effect by CSS gradient as follows:
.hidden {display:none;}
.wrap {
line-height: 1.2em;
background-color: orange;
background-image: linear-gradient(transparent 50%, green 50%);
background-size: 100% 2.4em;
}
<div class="wrap">
<div class="box">xx</div>
<div class="box">xx</div>
<div class="box hidden">xx</div>
<div class="box">xx</div>
<div class="box">xx</div>
<div class="box">xx</div>
<div class="box">xx</div>
</div>
Pseudo-selectors don't stack, so your :not doesn't affect the :nth-child (nor would it affect :nth-of-type etc.
If you can resort to jQuery, you can use the :visible pseudo-selector there, although that's not a part of the CSS spec.
If you're generating the HTML and can change that, you can apply odd/even with logic at run-time, eg in PHP:
foreach ($divs AS $i => $div) {
echo '<div class="box ' . ($i % 2 ? 'even' : 'odd') . '">x</div>';
}
Even trying to do something tricky like
.box[class='box']:nth-of-type(even)
doesn't work, because the psuedo-selector doesn't even stack onto the attribute selector.
I'm not sure there's any way to do this purely with CSS - I can't think of any right now.
Here's a CSS-only solution:
.box {
background: orange;
}
.box:nth-child(even) {
background: green;
}
.box.hidden {
display: none;
}
.box.hidden ~ .box:nth-child(odd) {
background: green;
}
.box.hidden ~ .box:nth-child(even) {
background: orange;
}
<div class="wrap">
<div class="box">xx</div>
<div class="box">xx</div>
<div class="box hidden">xx</div>
<div class="box">xx</div>
<div class="box">xx</div>
<div class="box">xx</div>
<div class="box">xx</div>
</div>
Since my rows are being hidden with js, I found that the easiest approach for me was to just add an additional hidden row after each real row that I hide, and remove the hidden rows when I show the real rows again.
Hide the rows you want to hide calling .hide() for each table row, then call
$("tr:visible:even").css( "background-color", "" ); // clear attribute for all rows
$("tr:visible:even").css( "background-color", "#ddddff" ); // set attribute for even rows
Add your table name to the selector to be more specific. Using :even makes it skip the Header row.
As #Fateh Khalsa pointed out, I had a similar problem and since I was manipulating my table with JavaScript (jQuery to be precise), I was able to do the following:
(Note: This assumes use of JavaScript/jQuery which the OP did not state whether or not would be available to them. This answer assumes yes, it would be, and that we may want to toggle visibility of hidden rows at some point.)
Inactive records (identified with the CSS class "hideme") are currently visible.
Visitor clicks link to hide inactive records from the list.
jQuery adds "hidden" CSS class to "hideme" records.
jQuery adds additional empty row to the table immediately following the row we just hid, adding CSS classes "hidden" (so it doesn't show) and "skiprowcolor" so we can easily identify these extra rows.
This process is then reversed when the link is clicked again.
Inactive records (identified with the CSS class "hideme") are currently hidden.
Visitor clicks link to show inactive records from the list.
jQuery removes "hidden" CSS class to "hideme" records.
jQuery removes additional empty row to the table immediately following the row we just showed, identified by CSS class "skiprowcolor".
Here's the JavaScript (jQuery) to do this:
// Inactive Row Toggle
$('.toginactive').click(function(e) {
e.preventDefault();
if ($(this).hasClass('on')) {
$(this).removeClass('on'); // Track that we're no longer hiding rows
$('.wrap tr.hideme').removeClass('hidden'); // Remove hidden class from inactive rows
$('.wrap tr.skiprowcolor').remove(); // Remove extra rows added to fix coloring
} else {
$(this).addClass('on'); // Track that we're hiding rows
$('.wrap tr.hideme').addClass('hidden'); // Add hidden class from inactive rows
$('.wrap tr.hideme').after('<tr class="hidden skiprowcolor"></tr>');
// Add extra row after each hidden row to fix coloring
}
});
The HTML link is simple
Hide/Show Hidden Rows
scss for #tim answer's above, to keep class name changes to a minimum
$selector: "box";
$hidden-selector: "hidden";
.#{$selector} {
background: orange;
:nth-child(even) {
background: green;
}
&.#{$hidden-selector} {
display: none;
}
&.#{$hidden-selector} ~ {
.#{$selector} {
&:nth-of-type(odd) {
background: green;
}
&:nth-of-type(even) {
background: orange;
}
}
}
}
Another way, albeit on the fringe side, is to have an extra <tbody> and either move or copy rows there. Or, an extra div wrapper if using OPs example. Copying easiest of course in regards to restoring etc.
This approach can be useful in some cases.
Below is a simple example where rows are moved when filtered. And yes, it is ranking of stripper names, found it fitting as we are talking stripes ... hah
const Filter = {
table: null,
last: {
tt: null,
value: ''
},
name: function (txt) {
let tb_d = Filter.table.querySelector('.data'),
tb_f = Filter.table.querySelector('.filtered'),
tr = tb_d.querySelectorAll('TR'),
f = 0
;
tb_f.innerHTML = '';
if (txt.trim() == '') {
tb_d.classList.remove('hide');
} else {
txt = txt.toLowerCase();
for (let i = 0; i < tr.length; ++i) {
let td = tr[i].querySelectorAll('TD')[1];
if (td.textContent.toLowerCase().includes(txt)) {
tb_f.appendChild(tr[i].cloneNode(true));
f = 1;
}
}
if (f)
tb_d.classList[f ? 'add' : 'remove']('hide');
}
},
key: function (e) {
const v = e.target.value;
if (v == Filter.last.value)
return;
Filter.last.value = v;
clearTimeout(Filter.last.tt);
Filter.last.tt = setTimeout(function () { Filter.name(v); }, 200);
}
};
Filter.table = document.getElementById('table');
Filter.table.addEventListener('keyup', Filter.key);
table {
width: 200px;
border: 3px solid #aaa;
}
tbody tr { background: #e33; }
tbody tr:nth-child(even) { background: #e3e; }
.hide { display: none; }
<table id="table">
<thead>
<tr><th></th><th><input type="text" id="filter" data-keyup="filter" /></th></tr>
<tr><th>#</th><th>Name</th></tr>
</thead>
<tbody class="filtered">
</tbody>
<tbody class="data">
<tr><td>1</td><td>Crystal</td></tr>
<tr><td>2</td><td>Tiffany</td></tr>
<tr><td>3</td><td>Amber</td></tr>
<tr><td>4</td><td>Brandi</td></tr>
<tr><td>5</td><td>Lola</td></tr>
<tr><td>6</td><td>Angel</td></tr>
<tr><td>7</td><td>Ginger</td></tr>
<tr><td>8</td><td>Candy</td></tr>
</tbody>
</table>
You can use another type of CSS selector: tbody > tr:nth-of-type(odd)
to only target tr nodes, and then, instead of using class names to hide the rows, simply wrap them with some element (which hides them), so the CSS selector would only match odd table rows:
const searchElem = document.querySelector('input');
const tableElem = document.querySelector('table');
const tableBody = document.querySelector('tbody');
function search() {
const str = searchElem.value.toLowerCase();
const rows = tableElem.querySelectorAll('tr');
// remove previous wrappers
// https://stackoverflow.com/a/48573634/104380
tableBody.querySelectorAll('div').forEach(w => {
w.replaceWith(...w.childNodes)
});
// create a wrapper which hides its content:
const wrapper = document.createElement("div");
wrapper.setAttribute('hidden', true);
rows.forEach(function(row){
const text = row.textContent.toLowerCase();
if (str.length && !text.includes(str)) {
// replace row with wrapper and put the row inside it
row.replaceWith(wrapper);
wrapper.appendChild(row);
}
});
}
searchElem.addEventListener('keyup', search);
tbody > tr:nth-of-type(odd) {
background: pink
}
<input type="search" placeholder="search">
<table>
<tbody>
<tr><td>Apple<td>220
<tr><td>Watermelon<td>465
<tr><td>Orange<td>94
<tr><td>Pear<td>567
<tr><td>Cherry<td>483
<tr><td>Strawberry<td>246
<tr><td>Nectarine<td>558
<tr><td>Grape<td>535
<tr><td>Mango<td>450
<tr><td>Blueberry<td>911
<tr><td>Pomegranate<td>386
<tr><td>Carambola<td>351
<tr><td>Plum<td>607
<tr><td>Banana<td>292
<tr><td>Raspberry<td>912
<tr><td>Mandarin<td>456
<tr><td>Jackfruit<td>976
<tr><td>Papaya<td>200
<tr><td>Kiwi<td>217
<tr><td>Pineapple<td>710
<tr><td>Lime<td>983
<tr><td>Lemon<td>960
<tr><td>Apricot<td>647
<tr><td>Grapefruit<td>861
<tr><td>Melon<td>226
<tr><td>Coconut<td>868
<tr><td>Avocado<td>385
<tr><td>Peach<td>419
</tbody>
</table>
Is there a way to automatically justify words using letter spacing, each in its row, to a defined width, using CSS?
For example, "Something like this" would look, well, something like this:
Is there a non-obtrusive way to apply such styling to my text? I believe pure CSS doesn't have this option (at least not with CSS versions before 3, CSS3 seems to have a text-justify property, but it's not well supported yet), so js solutions would be fine also.
Here's a script which can do it. It isn't pretty, but maybe you can hack it to meet your needs. (Updated to handle resizing)
function SplitText(node) {
var text = node.nodeValue.replace(/^\s*|\s(?=\s)|\s*$/g, "");
for (var i = 0; i < text.length; i++) {
var letter = document.createElement("span");
letter.style.display = "inline-block";
letter.style.position = "absolute";
letter.appendChild(document.createTextNode(text.charAt(i)));
node.parentNode.insertBefore(letter, node);
var positionRatio = i / (text.length - 1);
var textWidth = letter.clientWidth;
var indent = 100 * positionRatio;
var offset = -textWidth * positionRatio;
letter.style.left = indent + "%";
letter.style.marginLeft = offset + "px";
//console.log("Letter ", text[i], ", Index ", i, ", Width ", textWidth, ", Indent ", indent, ", Offset ", offset);
}
node.parentNode.removeChild(node);
}
function Justify() {
var TEXT_NODE = 3;
var elem = document.getElementById("character_justify");
elem = elem.firstChild;
while (elem) {
var nextElem = elem.nextSibling;
if (elem.nodeType == TEXT_NODE)
SplitText(elem);
elem = nextElem;
}
}
#character_justify {
position: relative;
width: 40%;
border: 1px solid red;
font-size: 32pt;
margin: 0;
padding: 0;
}
#character_justify * {
margin: 0;
padding: 0;
border: none;
}
<body onload="Justify()">
<p id="character_justify">
Something<br/> Like
<br/> This
</p>
</body>
The css only solution is text-justify: distribute https://www.w3.org/TR/css-text-3/#text-justify but the support is still very poor.
A small experiment using text-align-last: justify and adding spaces between letters.
div{
display:inline-block;
text-align: justify;
text-align-last: justify;
letter-spacing: -0.1em;
}
<div>
S o m e t h i n g<br>
l i k e<br>
t h i s
</div>
I know this is an old topic, but I faced this the other night. And found a suitable solution using tables.
Every letter shall be put into a <td> </td> I know it looks tedious, but if you wanna do this, it would be for a word or two, right? Or you always can use JS to fill it if is too much. However, this is only CSS and very versatile solution.
Using letter-spacing the letters get distributed properly. You should play around with it, depending on the width of the table.
#justify {
width: 300px;
letter-spacing: 0.5em;
}
<table id="justify">
<tbody>
<tr>
<td>J</td>
<td>U</td>
<td>S</td>
<td>T</td>
<td>I</td>
<td>F</td>
<td>Y</td>
</tr>
</tbody>
</table>
See the example here
Crossbrowser safe, virtually nothing shall differ. Is just CSS.
I used it in My website which is in english and spanish.
the subtitle under my name in spanish has an additional letter and it will step out the width. Using the tables explained above, it gets distributed to the same width automatically. Spacing it manually I'd had to define a whole condition for each language to go around that.
Here is an other aproach using a jQuery snippet I wrote for this question : Stretch text to fit width of div :
DEMO
HTML :
<div class="stretch">Something</div>
<div class="stretch">Like</div>
<div class="stretch">This</div>
jQuery :
$.fn.strech_text = function () {
var elmt = $(this),
cont_width = elmt.width(),
txt = elmt.html(),
one_line = $('<span class="stretch_it">' + txt + '</span>'),
nb_char = elmt.text().length,
spacing = cont_width / nb_char,
txt_width;
elmt.html(one_line);
txt_width = one_line.width();
if (txt_width < cont_width) {
var char_width = txt_width / nb_char,
ltr_spacing = spacing - char_width + (spacing - char_width) / nb_char;
one_line.css({
'letter-spacing': ltr_spacing
});
} else {
one_line.contents().unwrap();
elmt.addClass('justify');
}
};
$(document).ready(function () {
$('.stretch').each(function () {
$(this).strech_text();
});
});
Needed this too, so I've bundled the suggested technique in a simple to use jquery-plugin you can find here: https://github.com/marc-portier/jquery-letterjustify#readme.
It uses the same procedure at its core, and adds some options to tweak.
Comments welcome.
Found another way to achieve this with pure CSS, alas you need to spell out your words.
In my situation, this was the only solution that worked (some letters had classes), plus it also produced the straightest right-alignment among answers here, without using hacks.
.box {
width: min-content;
border: solid red;
}
.word {
display: flex;
justify-content: space-between;
}
<div class="box">
<div class="word">
<span>S</span>
<span>o</span>
<span>m</span>
<span>e</span>
<span>t</span>
<span>h</span>
<span>i</span>
<span>n</span>
<span>g</span>
<span> </span>
<span>w</span>
<span>i</span>
<span>c</span>
<span>k</span>
<span>e</span>
<span>d</span>
</div>
<div class="word">
<span>t</span>
<span>h</span>
<span>i</span>
<span>s</span>
<span> </span>
<span>w</span>
<span>a</span>
<span>y</span>
</div>
<div class="word">
<span>c</span>
<span>o</span>
<span>m</span>
<span>e</span>
<span>s</span>
</div>
</div>
Again, I know this is REALLY old, but why not just put a space between each letter and then text-align:justify? Then each letter would be regarded as a 'word' and justified accordingly
An alternate way to handle this might be to use the "vw" sizing unit. This unit type can be used in font size properties and represents a percent of the window's width.
Disclaimer: It is not exactly what you are looking for, but requires no scripting. It does adjust the text size, but will also scale to the width of your page.
For example,
.heading {
font-size: 4vw;
}
will make the width of one character in the current font 4% of the window width.
You could then use media queries if you wish to lock the font size to a minimum size based on the window's width.
#media only screen and (max-width: 768px) {
font-size: 2rem;
}
Use the browser inspector to play with the font-size property and tweak the value to what makes sense for your application.
The "vw" unit works in IE9+, iOS 8.3+ and Android 4.4+ and all other mainstream browsers. I wouldn't worry about the mobile support too much, as you can use media queries to put the right sizing for these devices as described above.
http://caniuse.com/#feat=viewport-units
https://css-tricks.com/viewport-sized-typography/
Viewport units are a powerful way to scale many different aspects of your site with little code.
I just made a JQuery script from table's Tony B approach.
Here is the JSFiddle https://jsfiddle.net/7tvuzkg3/7/
This script creates a table with each char in a row. This works with full sentence.
I'm not sure this is fully optimized.
justifyLetterSpacing("sentence");
function justifyLetterSpacing(divId) {
// target element
domWrapper = $('#' + divId).clone().html('');
// construct <td>
$('#' + divId).contents().each(function(index){
// store div id to td child elements class
var tdClass = divId ;
// split text
$textArray = $(this).text().split('');
// insert each letters in a <td>
for (var i = 0; i < $textArray.length; i++) {
// if it's a 'space', replace him by an 'html space'
if( $textArray[i] == " " ) {
$('<td>')
.addClass(tdClass)
.html(" ")
.appendTo(domWrapper);
}// if it's a char, add it
else{
$('<td>')
.addClass(tdClass)
.text($textArray[i])
.appendTo(domWrapper);
}
}
});
// create table
table =
$( "<table id='"+divId+"'/>" ).append(
$( "<tbody>" ).append(
$( "<tr>" ).append(
( domWrapper ).children('td')
)
)
);
// replace original div
$('#' + divId).replaceWith( table );
}
#sentence {
width : 100%;
background-color : #000;
color : #fff;
padding : 1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sentence">LOREM IPSUM DOLOR</div>
I usually try to write my answer on time. and this is exactly the same time (after 10 years) =)
myText.innerHTML = myText.textContent
.split(/\s+/g)
.map((line) => line.trim().split("").join(" "))
.join("<br>");
#myText {
display: inline-block;
text-align: justify;
text-align-last: justify;
letter-spacing: -0.125em;
font-family: sans-serif;
}
<div id="myText">Something like this</div>