Reputation: 693
I have a text like (03 Days 02 Night Package, Starts from $120). Is there anyway I can change the style of the numbers using only css. I know I can do this by adding an extra html tag or using jquery. Have been looking for this quite a time now but can't find anything. Any help would be appreciated.
Upvotes: 3
Views: 4111
Reputation: 11030
It is not possible, using pure CSS, to target only digits in a text.
The only thing you can do is change the font family of digits only.
This uses the unicode-range
(spec, MDN) directive. When using fonts from Google Fonts, it can be used as follows. I have selected the digits and dollar sign here, but any range of characters can be selected in the text
parameter.
@import url('https://fonts.googleapis.com/css?family=Raleway&text=0123456789$');
@import url('https://fonts.googleapis.com/css?family=Ranga');
p {
font-family: 'Raleway', 'Ranga', sans-serif;
}
<p>03 Days 02 Night Package, Starts from $120</p>
Because you only mention extra HTML tags and jQuery in your answer, I thought that it might be helpful to show you how to do it in vanilla JavaScript.
let elementToFindDigitsIn = document.querySelector('p');
elementToFindDigitsIn.innerHTML =
elementToFindDigitsIn
.textContent
.replace(/(\$?\d+)/g, '<span>$1</span>');
span {
color: blue;
}
<p>03 Days 02 Night Package, Starts from $120</p>
Indeed, as mentioned by @LGSon in a comment, it is also possible to give different classes to different numbers quite easily, this way.
let elementToFindDigitsIn = document.querySelector('p'),
count = 0;
elementToFindDigitsIn.innerHTML =
elementToFindDigitsIn
.textContent
.replace(/(\$?\d+)/g, (s) => {
let c = `num-${++count}`;
if (s[0] === '$') {
c += ' money';
}
return `<span class="${c}">${s}</span>`;
});
span {
color: blue;
}
span.money {
color: red;
}
span.num-2 {
color: purple;
}
<p>03 Days 02 Night Package, Starts from $120</p>
Upvotes: 7
Reputation: 491
Please try this code if you want to add similar color in a aal numbers that is available in your text.
<style>
p span{
color:red;
}
</style>
<p><span>03</span> Days <span>02</span> Night Package, Starts from <span>$120</span></p>
But If you want to add different color then you can add this css and html in your file.
<style>
p span:nth-child(1){
color:red;
}
p span:nth-child(2){
color:green;
}
p span:nth-child(3){
color:purple;
}
</style>
<p><span>03</span> Days <span>02</span> Night Package, Starts from <span>$120</span></p>
I hope it will helpful for you.
Upvotes: 1