Reputation: 128
Hello is there any way i can make 2nd word in different color with in a line by using css?
for ex:
<h2>Change color by css</h2>
here i want to change "color" will be different color.
Upvotes: 1
Views: 14881
Reputation: 393
In the HTML:
<h2>Change <span class ="color">color</span> by css</h2>
then the CSS in the stylesheet:
/* Replace blue with the colour you want */
.color { color: blue; }
Upvotes: 3
Reputation: 253308
For this to work (there is no :secondWord
pseudo-selector, sadly) you have to use JavaScript, so I'll offer a relatively simple suggestion that allows you to define a class-name to use as a style-hook:
Object.prototype.styleSecondWord = function(styleHook){
styleHook = styleHook || 'secondWord';
var text = '',
words = [];
for (var i = 0, len = this.length; i<len; i++){
words = (this[i].textContent || this[i].innerText).split(/\s+/);
if (words[1]) {
words[1] = '<span class="' + styleHook + '">' + words[1] + '</span>';
this[i].innerHTML = words.join(' ');
}
}
};
document.getElementsByTagName('h2').styleSecondWord('classNameToUse');
The above function updated in order to allow a specific element-type to be supplied (though it'll default to a span
if none is provided):
Object.prototype.styleSecondWord = function (styleHook, styleElem) {
styleHook = styleHook || 'secondWord';
styleElem = styleElem || 'span';
var open = '<' + styleElem + ' class="' + styleHook + '">',
close = '</' + styleElem + '>',
text = '',
words = [];
for (var i = 0, len = this.length; i < len; i++) {
words = (this[i].textContent || this[i].innerText).split(/\s+/);
if (words[1]) {
words[1] = open + words[1] + close;
this[i].innerHTML = words.join(' ');
}
}
};
document.getElementsByTagName('h2').styleSecondWord('classNameToUse', 'em');
Upvotes: 5
Reputation: 22161
You've to style an element in order to achieve that, so you'd have to add a span
and style it. Or maybe an em
or strong
if this particular word is used with some degree of emphasis.
Fiddle: http://jsfiddle.net/zrsaW/
I styled all span
in an h2
element but in real world, you'll usually add a class to this span and use this class as a selector to your styling instructions ;)
Upvotes: 0