- How To Style the Body of a Website With CSS
- Prerequisites
- Adding a Background Image To Your Website With CSS
- Changing the Color of Hyperlinked Text
- Conclusion
- Tutorial Series: How To Build a Website With CSS
- HTML Tag
- Syntax
- Example of the HTML tag:
- Result
- Example of the HTML tag used with the CSS color and line-height properties:
- Attributes
- How to style tag?
- Common properties to alter the visual weight/emphasis/size of text in tag:
- Coloring text in tag:
- Text layout styles for tag:
- Other properties worth looking at for tag:
- Css syntax html body
- Синтаксис
- Атрибуты
- Закрывающий тег
- Статьи по теме
How To Style the Body of a Website With CSS
In this tutorial, you will style the body of a webpage with a CSS rule. You will use this rule to apply and style a background image and set the font family for the webpage. You will also create a style rule that changes the color of all hyperlinked text to a color that better matches the demonstration website’s color palette.
This exercise will be used to recreate the style of the demonstration site but you can apply and modify the same rules used here for other HTML/CSS website projects.
Prerequisites
To follow this tutorial, make sure you have set up the necessary files and folders as instructed in a previous tutorial in this series How To Set Up You CSS and HTML Practice Project.
For this tutorial, we suggest you use the background image from the demonstration site which you can download from this link. You may use another image as your background, but make that sure that the image is large enough to fill the screen.
Note: To download the background image of the demonstration site, visit this link and click CTRL + Left Click (on Macs) or Right Click (on Windows) on the image and select “Save Image As” and save it as background-image.jpeg to your «image’ folder.
Once you have selected an image, make sure it’s saved as “background-image.jpeg” in your images folder. You are now ready to proceed to the next step.
Adding a Background Image To Your Website With CSS
To declare style rules for the body of a webpage, you will need to create a CSS rule for the body tag selector. These rules will then be applied to all elements that are placed inside the opening and closing tags that you added to the index.html file in the earlier tutorial How To Set Up Your CSS and HTML Website Project.
To add a background image to your site, create a CSS rule using the tag selector. Erase everything in your styles.css file (if you have been following along with this series) and add the following ruleset:
/* General Website Style rules */ body font-family: "Helvetica", Sans-Serif; background-image: url("../images/background-image.jpeg"); >
Take note of the highlighted file path, which tells the browser where to locate the background image. If you have changed the name or location of the image then you will need to adjust the file path here accordingly.
Let’s pause briefly to understand each of the declarations in this ruleset:
- /* General Website Style rules */ is a CSS comment, which is not displayed by the browser. Like HTML comments, CSS comments are useful for explaining and organizing your code for future reference. Notice that CSS comments open and close with /* and */ tags instead of tags used for HTML comments.
- The font-family: «Helvetica», Sans-Serif; declaration sets the font family (Helvetica) and generic font family (Sans-Serif) for all the text on the webpage. (Note that you can specify different font families for text content on the same webpage by adding CSS rules later on). The generic font family is given as a backup in case the first font family isn’t available and the browser needs to pick a back up font. You can explore other fonts by replacing “Helvetica” with other font names, such as Times , Courier , or Palatino .
- The background-image: url(» ../images/background-image.jpeg ;») declaration tells the browser to add a background image to the webpage using the file found with the specified file path. Note that you have prepended ../ to the file path name to tell the browser to locate the images folder in the directory above the directory that contains the file you are working in ( styles.css ).
Save your styles.css file and load the index.html page in your browser. For instructions on loading an HTML file, please visit our tutorial step How To View An Offline HTML File In Your Browser.
You should receive a page with no content except for the background image:
If you don’t receive an image, check to make sure your file path is correct and that there are no errors in your index.html file and styles.css file.
Changing the Color of Hyperlinked Text
Next, we’ll add a CSS rule that changes the color of all hyperlinked text to a color that better matches the website color palette.
At the bottom of your styles.css file, add the following ruleset:
Conclusion
You should now have a webpage with a large background image. In addition, you declared a font family that will be applied when you begin to add text content. Using rulesets like these allow you to change the font and background image of a webpage by creating a ruleset for the body tag selector. Finally, you created a style rule that specifies the color of any hyperlinked text you add to the page.
In the next tutorial, you’ll recreate the header section of the demonstration website.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Tutorial Series: How To Build a Website With CSS
This tutorial is part of a series on creating and customizing this website with CSS, a stylesheet language used to control the presentation of websites. You may follow the entire series to recreate the demonstration website and gain familiarity with CSS or use the methods described here for other CSS website projects.
Before proceeding, we recommend that you have some knowledge of HTML, the standard markup language used to display documents in a web browser. If you don’t have familiarity with HTML, you can follow the first ten tutorials of our series How To Build a Website With HTML before starting this series.
HTML Tag
The tag defines a web page content (text, images, links, etc.). It is placed inside the element, after the element. In an HTML document, we can use only one tag.
Commonly, a list of content-specific CSS classes is placed within the element allowing JavaScript developers and designers to target pages easily. Even if these classes are not used, they won’t cause any problems.
Syntax
The
tag comes in pairs. The content is written between the opening () and closing () tags.Example of the HTML tag:
html> html> head> title>Title of the document title> head> body> p>Content of the document p> body> html>
Result
Example of the HTML tag used with the CSS color and line-height properties:
html> html> head> title>Title of the document title> style> body < color: #444444; line-height: 1.5; > style> head> body> h1>HTML body tag example h1> p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> body> html>
Attributes
Attribute | Value | Description |
---|---|---|
alink | color | Defines the color of the active link. Not used in HTML5. |
background | URL | Defines the background image. Not used in HTML5. |
bgcolor | color | Defines the background color. Not used in HTML5. |
link | color | Defines the color of unvisited links. Not used in HTML5. |
text | color | Defines the color of the text in a document. Not used in HTML5. |
vlink | color | Defines the color of the visited link. Not used in HTML5. |
How to style tag?
Common properties to alter the visual weight/emphasis/size of text in tag:
- CSS font-style property sets the style of the font. normal | italic | oblique | initial | inherit.
- CSS font-family property specifies a prioritized list of one or more font family names and/or generic family names for the selected element.
- CSS font-size property sets the size of the font.
- CSS font-weight property defines whether the font should be bold or thick.
- CSS text-transform property controls text case and capitalization.
- CSS text-decoration property specifies the decoration added to text, and is a shorthand property for text-decoration-line, text-decoration-color, text-decoration-style.
Coloring text in tag:
- CSS color property describes the color of the text content and text decorations.
- CSS background-color property sets the background color of an element.
Text layout styles for tag:
- CSS text-indent property specifies the indentation of the first line in a text block.
- CSS text-overflow property specifies how overflowed content that is not displayed should be signalled to the user.
- CSS white-space property specifies how white-space inside an element is handled.
- CSS word-break property specifies where the lines should be broken.
Other properties worth looking at for tag:
- CSS text-shadow property adds shadow to text.
- CSS text-align-last property sets the alignment of the last line of the text.
- CSS line-height property specifies the height of a line.
- CSS letter-spacing property defines the spaces between letters/characters in a text.
- CSS word-spacing property sets the spacing between words.
Css syntax html body
Элемент предназначен для хранения содержания веб-страницы (контента), отображаемого в окне браузера. Информацию, которую следует выводить в документе, следует располагать именно внутри контейнера . К такой информации относится текст, изображения, теги, скрипты JavaScript и т.д.
Тег также применяется для определения цветов ссылок и текста на веб-странице. Подобная практика в HTML 4 осуждается и взамен для указания цветовой схемы рекомендуется использовать стили, применяя их к селектору BODY . Тем не менее, большинство атрибутов до сих пор поддерживается разными браузерами.
Часто тег используется для размещения обработчика событий, например, onload, которое выполняется после того, как документ завершил загрузку в текущее окно или фрейм.
Открывающий и закрывающий теги на веб-странице не являются обязательными, однако хорошим стилем считается их использование, чтобы определить начало и конец HTML-документа.
Синтаксис
Атрибуты
alink Устанавливает цвет активной ссылки. background Задает фоновый рисунок на веб-странице. bgcolor Цвет фона веб-страницы. bgproperties Определяет, прокручивать фон совместно с текстом или нет. bottommargin Отступ от нижнего края окна браузера до контента. leftmargin Отступ по горизонтали от левого края окна браузера до контента. link Цвет ссылок на веб-странице. rightmargin Отступ от правого края окна браузера до контента. scroll Устанавливает, отображать полосы прокрутки или нет. text Цвет текста в документе. topmargin Отступ от верхнего края окна браузера до контента. vlink Цвет посещенных ссылок.
Также для этого тега доступны универсальные атрибуты и события.
Закрывающий тег
Открывающий и закрывающий теги не обязательны.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat.
Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
Результат текущего примера показан на рис. 1. При использовании события onload тега выполняется скрипт, написанный на языке JavaScript, в данном случае он выводит сообщение, что документ загружен.
Рис. 1. Всплывающее окно в документе