Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS After x Characters

Tags:

html

jquery

css

I have a text string inside a td, as below:

<td>This is a long line</td>

What I want to be able to do is change the font size of all the characters after the first seven. Now I know I could do the following:

<td>This is<span class="different"> a long line</span></td>

Unfortunately I can't do that, as this is part of a table generated from a php while function, and the only way to target this is by using CSS nth-child() or similar, as it only occurs in one row. I do not think a PHP solution would work.

So how can I target this? I'm basically looking for something which would do the following:

#table2 td:nth-child(6) characters(n+7) { font-size: 8px; }

Also, if the above isn't possible, alternatively an option would be to apply a different CSS to the first seven characters, and apply the nth-child to the whole td, which will be overridden by the function to add CSS to the first seven.

CSS solution preferred, JS/jQuery welcome. If more information is needed, please comment and I will try and add.

like image 990
CalvT Avatar asked Aug 03 '26 13:08

CalvT


1 Answers

Using pure CSS I'd say this is not possible. CSS works on elements and attributes, and text inside an element is neither of those.

But since you're also OK with jQuery, here goes:

$("td").each(function() {
  var text = $(this).text();
  var part1 = text.substring(0, 7);
  var part2 = text.substring(7);
  $(this).html(part1 + "<i>" + part2 + "</i>");
})
td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>This is a long line</td>
    <td>Short</td>
  </tr>
  <tr>
    <td colspan=2>Supermagically long line</td>
  </tr>
</table>

Short explanation: get the text for every td, cut at position 7, and put it back in with extra added tags.

like image 79
Peter B Avatar answered Aug 07 '26 12:08

Peter B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!