If you're struggling with formatting text to be easily styled with CSS, the key is transforming it into a JSON array of strings.
[
"Solution,",
"Given, f(x) = 3x",
"g(x) = x + 2",
"fog(x) = 18",
"To find: x = ?,",
"Now,",
"fog(x) = 18",
"or, f(x + 2) = 18",
"or, 3(x + 2) = 18",
"or, x + 2 = 6",
"∴ x = 4"
]
To achieve this transformation and make the text style-able, you can use a function like the one demonstrated below using plain Javascript and CSS grid:
[...document.querySelectorAll('math-element')].forEach(el => {
// reset, in case you run this more than once...
el.innerHTML = '';
// we need JSON.parse as dataset.text is a string
JSON.parse(el.dataset.text).forEach(text => {
const div = document.createElement('div');
// split each row by `=` sign, if it has any
text.split('=').forEach(t => {
const span = document.createElement('span');
if (text.split('=').length < 2) {
// adds `.single` to items which are single on their row
span.classList.add('single');
}
span.innerHTML = t;
el.appendChild(span);
});
// add a `<hr>` after each element
const separator = document.createElement('hr')
el.appendChild(separator);
})
})
math-element {
display: grid;
grid-template-columns: auto 1fr;
}
math-element hr {
display: none;
}
math-element span {
grid-column-start: 1;
text-align: right;
padding: 0 2px 0 1rem;
}
math-element span:not(.single) {
font-style: italic;
}
math-element span.single {
text-align: left;
padding-top: .5rem;
font-style: normal;
}
math-element span + span {
grid-column-start: 2;
text-align: left;
padding: 0 2px;
}
math-element span + span:before {
content: '=';
}
<math-element data-text='["Solution,","Given, f(x) = 3x","g(x) = x + 2","fog(x) = 18","To find: x = ?,","Now,","fog(x) = 18","or, f(x + 2) = 18","or, 3(x + 2) = 18","or, x + 2 = 6","∴ x = 4"]'></math-element>
If coding the values directly as a string doesn't suit your needs, you can dynamically create the elements and iterate over the data without storing them as strings.
In case the CSS grid syntax seems complex, an alternative could be utilizing <table>
, <tr>
, and <td>
tags for simpler selectors, although it's not generally recommended.
The usage of <hr>
tags marks the end of each "row" due to CSS grid requirements. Alternatively, nesting the row contents within a single element like a <div>
could be considered along with adjusting column widths.
You have the liberty to customize the CSS properties such as removing font-style
, tweaking padding
values, etc.
Lastly, if a "row" contains multiple =
signs, additional CSS rules must be added to align these elements properly.
By modifying the number of columns in the rule and updating accordingly, you can personalize the layout as needed:
math-element {
grid-template-columns: auto auto 1fr;
}
Feel free to adapt and enhance the CSS styles to match your design preferences.