Home > Software engineering >  Apply first 2 characters of string another styling
Apply first 2 characters of string another styling

Time:11-08

Is it possible to style the first 2 characters of a message another styling?

::first-letter

Does not do the trick, also looked enter image description here

NOTE, I can not change the HTML.

<h4 >10 Mar. 2022</h4>

CodePudding user response:

This can't be done with pure CSS since there is no way of (dynamically) selecting the first 'word'.


Consider a alternative that wraps the first part in an <em></em> that can be styled with some CSS.

const e = document.querySelector('.date');
const t = e.innerHTML.split(' ');

e.innerHTML = `<em class='up'>${t.shift()}</em> ${t.join(' ')}`
.up {
  color: darkblue;
  font-size: x-large;
  position: absolute;
  top: 5px;
  font-style: unset;
}

h4 {
  color: lightblue;
  margin-top: 30px;
}
<h4 >10 Mar. 2022</h4>

CodePudding user response:

You can use a mixture of JS and css to achieve what you are looking for. First, just split the different parts (day/month/year) into different spans and add styling accordingly. An example as follows.

var text = $('.date').text();
var textArr = text.split(/\s /);

$('.date').html(`<span >${textArr[0]}</span>&nbsp;
                <span >${textArr[1]}</span>&nbsp;
                <span >${textArr[2]}</span>`);
.month {
  color: red;
}

.day {
  color: blue;
}

.year {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4 >10 Mar. 2022</h4>

  •  Tags:  
  • css
  • Related