The font-family in CSS controls which font to use in HTML document. For example, we can set font-family to Arial.
We can set many optional font names for font-family in CSS, the browser will use the first value it recognizes in the website visitor's system.
There are two types of font-family values:
We must separate each font name with a comma, and add quotates to font-family name with whitespace.
The fontFamily
property sets or gets
a list of font-family names or generic-family names in Javascript.
fontFamily |
Yes | Yes | Yes | Yes | Yes |
Return the fontFamily property:
var v = object.style.fontFamily
Set the fontFamily property:
object.style.fontFamily='font1, font2, etc.|initial|inherit'
Value | Description |
---|---|
font1, font2, etc. | font-family names or generic-family names |
initial | Sets to default value. |
inherit | Inherits from parent element. |
Default Value: | not specified |
---|---|
Return Value: | A string representing the font name |
CSS Version | CSS1 |
A demonstration of possible font names.
<!DOCTYPE html>
<html>
<body>
<!--from ww w .ja v a 2 s . c om-->
<p id="myP">This is a paragraph.</p>
<select onchange="myFunction(this);" size="13">
<option>Georgia</option>
<option>Palatino Linotype</option>
<option>Book Antiqua</option>
<option>Times New Roman</option>
<option>Arial</option>
<option>Helvetica</option>
<option>Arial Black</option>
<option>Impact</option>
<option>Lucida Sans Unicode</option>
<option>Tahoma</option>
<option>Verdana</option>
<option>Courier New</option>
<option>Lucida Console</option>
</select>
<script>
function myFunction(selectTag) {
var listValue = selectTag.options[selectTag.selectedIndex].text;
document.getElementById("myP").style.fontFamily = listValue;
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to set the font name.
<!DOCTYPE html>
<html>
<body>
<p id="myP">This is a paragraph.</p>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from ww w . j av a2s.c o m-->
document.getElementById("myP").style.fontFamily = "Impact,Charcoal,sans-serif";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to get the font name.
<!DOCTYPE html>
<html>
<body>
<p id="myP" style="font-family:Arial,Helvetica,sans-serif;">This is a paragraph.</p>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from w w w .j av a2 s .com-->
console.log(document.getElementById("myP").style.fontFamily);
}
</script>
</body>
</html>
The code above is rendered as follows: