Css внутри 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.

Читайте также:  Смена цвета в python

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:

Webpage with background image only

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.

Источник

Как добавить CSS стили в body веб страницы

В одном из проектов понадобилось добавить новые стили к одной определённой странице, но шаблон позволял менять только содержимое после тега . Чтобы не добавлять ненужные стили на весь сайт, а вставить их только для одной страницы, рассмотрим, какие есть варианты добавления CSS внутри .

1.

Правильно загружать внешние CSS файлы на странице следующим образом:

То есть файлы стилей должны быть загружены внутри тега .

Тем не менее с помощью функции JavaScript можно дополнить код из тела страницы:

  

Либо вы можете добавить динамические определения, такие как:

  

2.

Ещё один вариант — просто вставить нужные стили после тега :

   * p  * p 

"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. "

"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. "

"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. "

Не уверен по поводу валидности получаемого кода, но CSS работает!

3.

Этот вариант также работает:

Но только если не содержит /css в rel (то есть следующий вариант НЕ работает):

4.

Вы можете поместить теги внутри .

Источник

How can I insert CSS styles inside independent of specific elements?

Inline CSS has the drawback that I can’t use CSS classes, which is something I need to do. Is there a way to define internal CSS (e.g. a fragment in the element?

This would be much easier for me because I could create a self-contained HTML snippet with a method in my server code. This kind of method is necessary because I don’t control the section. It is owned by a commercial product. I can only insert content inside the .

I have seen other websites (like https://amazon.com) where they appear to have several style tags inside the .

There is a huge gap between theory and practice. Many sites use in the body.

The editors decided against it. But maybe there will be a change in the future: https://github.com/whatwg/html/issues/1605

OK — would custom web components be of use — they can contain their own css that does not propogate to the parent DOM and is available within the component immediately

5 Answers 5

Under the premise, you don’t care about invalid HTML in relation of inside (which is not that uncommon), you can assign unique identifier i.e.:

 .my-class-1 
Fragment Content
.my-class-2
Fragment Content
.my-fragment-1 .my-class
Fragment Content
.my-fragment-2 .my-class
Fragment Content
#my-style-1 + div
Fragment Content
#my-style-2 + div
Fragment Content

What can you do if there is a big difference between the specification and the daily practice? Change the daily practice, or adapt the spec?

To have no access to the section is somehow an unsual practice. But see this discussion. It seems that it is implemented in HTML5.2 W3C . should be used with care . . At least be aware of Flash of unstyled content what is usualy caused by styles placed in the and be loaded afterwards. That’s why I prevent it. FOUC and FOIT is not very user friendly.

the simpler answer to your question is «Yes» and I’ll elaborate on this with several examples below. A tag will work wherever you place it within either the or the .

A style tag placed in the tag technically does violate HTML syntax rules, it’s surprisingly common in practice, even among some larger corporations.

There are several different methods for including -level tags in your project.

1. Pure HTML tags (the static method)

If you have all the styles you need already written up and there are no dynamic pieces needed, you can simply write those styles into a tag statically and include those in the code, as seen in this example below:

   

This is a title

This is some text.

.custom-widget < display: block; padding: 20px; border: 5px double red; >.custom-widget h1 < text-transform: uppercase; >.custom-widget h1::first-letter < font-size: 150%; >.custom-widget p

2. Writing the styles into a tag as text using JavaScript

If you need to load the styles into your tag dynamically and you simply need plain text styles that you will not need to change much after creating them. You can create the block and then inject the CSS styles as plain text as desired, as seen in this example below:

const counter = document.getElementById('counter'); let count = +counter.dataset.count; const customWidgetStyle = document.querySelector('.custom-widget style'), countdown = setInterval(() => < if (count--) < counter.innerText = `Importing CSS in $…`; > else < clearInterval(countdown); counter.remove(); customWidgetStyle.innerHTML = ` .custom-widget < display: block; padding: 20px; border: 5px double red; >.custom-widget h1 < text-transform: uppercase; >.custom-widget h1::first-letter < font-size: 150%; >.custom-widget p < font-style: italic; >`; > >, 1000);
   

This is a title

This is some text.

Importing CSS in 3…

3. Creating cssRules styles into a tag using the JavaScript CSSStyleSheet.insertRule() method

If you need even more flexibility with how you add your styles, you can use the CSSStyleSheet.insertRule() (MDN docs), which will dynamically allow you to add and manage the styles more granularly. This may be overkill for your specific need but there’s a lot of power, flexibility, and control when working with the CSSOM.

Here is an example of this method, in which I use an addStylesheetRules function example defined on the MDN docs page for insertRule under the heading Examples, here:

const addStylesheetRules = (rules, stylesheet) => < if (stylesheet === undefined) < const style = document.createElement('style'); stylesheet = style.sheet; document.head.appendChild(style); >for (let i = 0; i < rules.length; i++) < let j = 1, propStr = ''; rule = rules[i]; const selector = rule[0]; if (Array.isArray(rule[1][0])) < rule = rule[1]; j = 0; >for (let pl = rule.length; j < pl; j++) < const prop = rule[j]; propStr += prop[0] + ': ' + prop[1] + (prop[2] ? ' !important' : '') + ';\n'; >stylesheet.insertRule(selector + '', stylesheet.cssRules.length); > > const customWidget = document.querySelector('.custom-widget'), customWidgetStyleTag = document.createElement('style'); customWidget.appendChild(customWidgetStyleTag); const customWidgetStylesheet = customWidgetStyleTag.sheet; addStylesheetRules([ ['.custom-widget', ['display', 'block'], ['padding', '20px'], ['border', '5px double red'] ], ['.custom-widget h1', ['text-transform', 'uppercase'] ], ['.custom-widget h1::first-letter', ['font-size', '150%'] ], ['.custom-widget p', ['font-style', 'italic'] ] ], customWidgetStylesheet);
   

This is a title

This is some text.

Please let me know if there is any more context I can add to better answer your question.

Источник

Оцените статью