- How to set the font family for text with JavaScript?
- Using the style.fontFamily Property
- Syntax
- Parameters
- Example
- Using the style.setProperty Method
- Syntax
- Parameters
- Example
- Пример
- Результат
- Использование CSS стилей
- Пример
- Результат
- Атрибуты
- Как добавить стиль к тегу ?
- Распространенные свойства для изменения визуальной насыщенности/выделения/размера текста внутри тега :
- Цвет текста внутри тега :
- Стили форматирования текста для тега :
- Другие свойства для тега :
- CSS Button Tutorial – How to Styling HTML Buttons with CSS
- A simple “Get Started” button
- Then create the gradients:
- Then give the curved edge for the button
- How to Trigger a button on-hover event
- How to Add a Transparent Background to a CSS Button
- /* Text color */
- /* Remove background color */
- /* Border thickness, line style, and color */
- /* Adds curve to border corners */
- /* Make letters uppercase */
- /*button on hover*/
- Button with CSS Entities
- Button with click animation
- Full CSS: (SCSS)
- Button with an image
- Button with icons
- Conclusion
How to set the font family for text with JavaScript?
In this tutorial, we will learn how to set the font family for text with JavaScript.
The font-family is a CSS property that specifies a prioritized list containing one or more font family names and generic family names for the text of an HTML element. To set the font-family for text with JavaScript, we have multiple ways, and in this tutorial, we will discuss two of them −
Using the style.fontFamily Property
The style.fontFamily property sets a list of font family names and/or generic family names for the text. The browser will set the first value from the list that it recognizes. The element object contains this property, so first, the document.getElementById() method is used to access the element object, and then we use the style.fontFamily property to set the font family for text with JavaScript.
Syntax
const element = document.getElementById('id') element.style.fontFamily = family_name | generic_family | inherit | initial
In the above syntax, the ‘id’ is the id of an element. Using the document.getElementById() method we are accessing that element object and set the style.fontFamily property.
Parameters
- family_name − The name of one or multiple font families.
- generic_family − The name of one or multiple generic families.
- inherit − The font-family property is inherited by its parent element’s property.
- initial − The font-family property is set to default.
Example
In the below example, we have used the style.fontFamily property to set the font family for text with JavaScript. We have used a button “Set Font Family” click event to execute the “setFontFamily()” function that sets the font-family property of multiple elements.
html> head> style> div padding: 10px; margin: 5px 0px; background-color: aliceblue; > /style> /head> body> h3> Set the font family for text using i> style.fontFamily property /i> with JavaScript /h3> button onclick="setFontFamily()"> Set Font Family /button> br />br /> div id="text1"> This text will use Arial font family /div> div id="text2"> This text will use cursive font family /div> div id="text3"> This text will use Helvetica, sans-serif font family /div> div id="text4"> This text will use Georgia, serif font family /div> script> // 'Set Font Family' button click event handler function function setFontFamily() // all text elements const text1 = document.getElementById('text1') const text2 = document.getElementById('text2') const text3 = document.getElementById('text3') const text4 = document.getElementById('text4') // Set the font-family property using the style.fontFamily property text1.style.fontFamily = 'Arial' text2.style.fontFamily = 'cursive' text3.style.fontFamily = 'Helvetica, sans-serif' text4.style.fontFamily = 'Georgia, serif' > /script> /body> /html>
Using the style.setProperty Method
In JavaScript, any new or existing property of an HTML element can be set using the style.setProperty method. The style.setProperty method is a part of the element object, so to use this method, we need to access the element object using the document.getElementById() method and then we can use this method. In the property name parameter of the style.setProperty method, it should be ‘font-family’, and the value and priority will be as per the user.
Syntax
const element = document.getElementById('id') element.style.setProperty(property_name, value, priority)
In the above syntax, we access the element object of an HTML element that has an id of ‘id’ using the document.getElementById() method and then use the style.setProperty method.
Parameters
- property_name − The name of the property to be set.
- value − The new value of the property.
- priority − The priority of the property value (Optional).
Example
In the below example, we have used the style.setProperty method to set the font family for text with JavaScript. We have used an input field to take the user’s input for the list of font families. A button, “Set Font Family” is associated with a click event that executes the “setFontFamily()” function, which sets the font family of an element.
html> head> style> div padding: 10px; margin: 5px 0px; background-color: aliceblue; > /style> /head> body> h2> Set the font family for text using i> style.setProperty method /i> with JavaScript /h2> h4>Enter the list of font-families to set:/h4> input id="fonts" type="text" name="fonts" value="sans-serif"> button onclick="setFontFamily()"> Set Font Family /button> br />br /> div id="text"> This text will change it's font family according to the user's input! /div> script> // 'Set Font Family' button click event handler function function setFontFamily() const text = document.getElementById('text') // input field's value const fonts = document.getElementById('fonts').value // Set the font-family property using the style.setProperty method text.style.setProperty('font-family', fonts) > /script> /body> /html>
In this tutorial, we learned how to set the font family for text with JavaScript. We have seen two ways to set the font family using the style.fontFamily property and using the style.setProperty method. Users can follow these approaches to set the font family for text.
HTML тег
Содержимое тега пишется между открывающим тегами.
Пример
html> html> head> title>Заголовок документа title> head> body> h1>Вот наша кнопка.. h1> button type="button">Нажать button> body> html>
Результат
Использование CSS стилей
К тегу можно применять CSS стили для изменения внешнего вида кнопки, ее размера, цвета, шрифта текста и т.д.
Пример
html> html> head> title>Заголовок документа title> head> body> Обычная кнопка button type="button">Добавить в корзину button> hr /> Кнопка с красным текстом button type="button" style="color: red;">b>Книга HTML b> button> hr /> Кнопка с увеличенным размером шрифта button type="button" style="font: bold 14px Arial;">Загрузить книгу button>br /> body> html>
Результат
Атрибуты
У тега
Атрибут | Значение | Описание |
---|---|---|
autofocus | autofocus | Указывает браузеру, что кнопка должна получить фокус после загрузки страницы. |
disabled | disabled | Деактивирует кнопку. (Используется в случае, когда кнопка должна стать активной после выполнения какого-либо действия.) |
form | form_id | Указывает форму, к которой относится кнопка. Если кнопка относится к нескольким формам, то их идентификаторы (form_id) должны быть разделены пробелами. |
formaction | URL | Задаёт адрес, куда будут пересылаться данные формы при нажатии на кнопку. (Используется только для кнопок с атрибутом type=»submit»). |
formenctype | application/x-www-form- urlencoded multipart/form-data text/plain | Определяет способ кодирования данных формы перед отправкой на сервер. (Используется только для кнопок с атрибутом type=»submit»). все символы кодируются перед отправкой (значение по умолчанию). символы не кодируются пробелы заменяются знаком «+», но символы не кодируются. |
formmethod | Указывает метод HTTP запроса, который будет использован при отправке данных формы. (Используется только для кнопок с атрибутом type=»submit») | |
get | Передает данные формы в адресной строке («имя=значение»), которые добавляются к URL страницы после вопросительного знака и разделяются между собой амперсандом (&). (http://example.ru/doc/?name=Ivan&password=vanya) | |
post | Браузер устанавливает связь с сервером и посылает данные для обработки. | |
formnovalidate | formnovalidate | Отменяет проверку данных формы на корректность. (Используется только для кнопок с атрибутом type=»submit»). |
formtarget | Указывает, где показывать ответ после отправки формы. (Используется только для кнопок с атрибутом type=»submit»). | |
blank | открывает ответ в новом окне. | |
self | открывает ответ в текущем окне. | |
parent | открывает ответ в родительском фрейме. | |
top | открывает ответ во всю ширину окна. | |
name | name | Определяет имя кнопки. |
type | Определяет тип кнопки. | |
button | обычная кнопка | |
reset | кнопка, которая очищает форму от введенных данных | |
submit | кнопка для отправки данных формы | |
value | text | Устанавливает значение кнопки. |
Как добавить стиль к тегу ?
Распространенные свойства для изменения визуальной насыщенности/выделения/размера текста внутри тега :
- CSS свойство font-style задает стиль шрифта: normal | italic | oblique | initial | inherit
- CSS свойство font-family создает приоритетный список названий семейства шрифтов и/или общее имя шрифтов для выбранных элементов.
- CSS свойство font-size задает размер щрифта.
- CSS свойство font-weight устанавливает насыщенность шрифта.
- CSS свойство text-transform задает регистр текста (заглавные или строчные буквы).
- CSS свойство text-decoration устанавливает оформление текста. Оно является сокращенным свойством для text-decoration-line, text-decoration-color, text-decoration-style.
Цвет текста внутри тега :
Стили форматирования текста для тега :
- CSS свойство text-indent указывает размер отступа первой строки в текстовом блоке.
- CSS свойство text-overflow указывает, как будет отображаться пользователю строчный текст, выходящий за границы блока.
- CSS свойство white-space указывает, как будут отображены пробелы внутри элемента.
- CSS свойство word-break указывает перенос строки.
Другие свойства для тега :
- CSS свойство text-shadow добавляет тень к тексту.
- CSS свойство text-align-last выравнивает последнюю строку текста.
- CSS свойство line-height устанавливает межстрочный интервал.
- CSS свойство letter-spacing устанавливает расстояние между буквами/символами в тексте.
- CSS свойство word-spacing устанавливает расстояние между словами в тексте.
CSS Button Tutorial – How to Styling HTML Buttons with CSS
Buttons have become an inevitable part of front end development. Thus, it is important to keep in mind a few things before you start styling buttons. I have gathered some of the ways of styling buttons using CSS.
A simple “Get Started” button
First, create the button class itself:
Then create the gradients:
background-image: -webkit-linear-gradient(top, #eb94d0, #2079b0); background-image: -moz-linear-gradient(top, #eb94d0, #2079b0); background-image: -ms-linear-gradient(top, #eb94d0, #2079b0); background-image: -o-linear-gradient(top, #eb94d0, #2079b0); background-image: linear-gradient(to bottom, #eb94d0, #2079b0);
Then give the curved edge for the button
-webkit-border-radius: 28; -moz-border-radius: 28; border-radius: 28px; text-shadow: 3px 2px 1px #9daef5; -webkit-box-shadow: 6px 5px 24px #666666; -moz-box-shadow: 6px 5px 24px #666666; box-shadow: 6px 5px 24px #666666; font-family: Arial; color: #fafafa; font-size: 27px; padding: 19px; text-decoration: none;>
How to Trigger a button on-hover event
How to Add a Transparent Background to a CSS Button
/* Text color */
/* Remove background color */
/* Border thickness, line style, and color */
/* Adds curve to border corners */
/* Make letters uppercase */
border: none; color: white; padding: 16px 32px; text-align: center; display: inline-block; font-size: 16px; margin: 4px 2px; -webkit-transition-duration: 0.4s; /* Safari */ transition-duration: 0.4s; cursor: pointer; text-decoration: none; text-transform: uppercase; > .btn1
/*button on hover*/
Button with CSS Entities
.button span:after < content: '\00bb'; /* CSS Entities. To use HTML Entities, use →*/ position: absolute; opacity: 0; top: 0; right: -20px; transition: 0.5s;>.button:hover span < padding-right: 25px;>.button:hover span:after
Button with click animation
Full CSS: (SCSS)
$gray: #bbbbbb; * < font-family: 'Roboto', sans-serif;>.container < position: absolute; top:50%; left:50%; margin-left: -65px; margin-top: -20px; width: 130px; height: 40px; text-align: center; >.btn < color: #0099CC; /* Text color */ background: transparent; /* Remove background color */ border: 2px solid #0099CC; /* Border thickness, line style, and color */ border-radius: 70px; /* Adds curve to border corners */ text-decoration: none; text-transform: uppercase; /* Make letters uppercase */ border: none; color: white; padding: 16px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; -webkit-transition-duration: 0.4s; /* Safari */ transition-duration: 0.4s; cursor: pointer;>.btn1 < background-color: white; color: black; border: 2px solid #008CBA;>.btn1:hover < background-color: #008CBA; color: white; >&:active < letter-spacing: 2px ; >&:after < content:""; >>.onclic < width: 10px !important; height: 70px !important; border-radius: 50% !important; border-color:$gray; border-width:4px; font-size:0; border-left-color: #008CBA; animation: rotating 2s 0.25s linear infinite; &:hover < color: dodgerblue; background: white; >>.validate < content:""; font-size:16px; color: black; background: dodgerblue; border-radius: 50px; &:after < font-family:'FontAwesome'; content:" done \f00c"; >> b < outline:none; height: 40px; text-align: center; width: 130px; border-radius:100px; background: #fff; border: 2px solid #008CBA; color: #008CBA; letter-spacing:1px; text-shadow:0; font:< size:12px; weight:bold; >cursor: pointer; transition: all 0.25s ease; @keyframes rotating < from < transform: rotate(0deg); >to < transform: rotate(360deg); >>
function validate() < setTimeout(function() < $("#button").removeClass("onclic"); $("#button").addClass("validate", 450, callback); >, 2250); > function callback() < setTimeout(function() < $("#button").removeClass("validate"); >, 1250); >>);
Button with an image
Button with icons
button< border: none; border-radius: 50px;>html,body < font-size: 20px; min-height: 100%; overflow: hidden; font-family: "Helvetica Neue", Helvetica, sans-serif; text-align: center;>.text < padding-top: 50px; font-family: "Helvetica Neue", Helvetica, 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; >.text:hover< cursor: pointer; color: #1565C0;>.main < padding: 0px 0px 0px 0px; margin: 0; background-image: url("https://someimg"); text-align: center; background-size: 100% !important; background-repeat: no-repeat; width: 900px; height: 700px; >.icon-button < background-color: white; border-radius: 3.6rem; cursor: pointer; display: inline-block; font-size: 2rem; height: 3.6rem; line-height: 3.6rem; margin: 0 5px; position: relative; text-align: center; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; width: 3.6rem;>.icon-button span < border-radius: 0; display: block; height: 0; left: 50%; margin: 0; position: absolute; top: 50%; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; transition: all 0.3s; width: 0;>.icon-button:hover span < width: 3.6rem; height: 3.6rem; border-radius: 3.6rem; margin: -1.8rem;>.twitter span < background-color: #4099ff;>/* Icons */.icon-button i < background: none; color: white; height: 3.6rem; left: 0; line-height: 3.6rem; position: absolute; top: 0; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; transition: all 0.3s; width: 3.6rem; z-index: 10;>.icon-button .icon-twitter < color: #4099ff;>.icon-button:hover .icon-twitter
Conclusion
In this tutorial, you’ve learned how to customize buttons using CSS and a bit of Javascript if you need the “after click” function. You can also use CSS3ButtonGenerator to generate simple buttons. Feel free to ping me if you have any questions.