How to use css in html
How to use css in html
CSS for Beginners: What is CSS and How to Use it in Web Development?
HTML, CSS and JavaScript… 3 main languages of Web Front-end Development. In this article, I will cover the basics of CSS. So if you have no idea about CSS, or don’t know how to use it, this article is for you 🙂
We will have a look at what CSS is, how to write CSS rules and how to add them to HTML. As a pre-requisite, if you don’t know anything about Web Development, I recommend you to understand HTML first.
What is CSS?
CSS (Cascading Style Sheets) is a language for styling the webpage. We can change the appearance and the layout of the webpage by using CSS. We can also define how a website’s view changes in different screens like desktops, tablets, and mobile devices.
CSS is not a programming language, like C++ or JavaScript. However, CSS is not as easy as it seems. If you try to use it without understanding, you will have difficulties in web development. Therefore, learning CSS is as important as learning a programming language.
Let’s continue with an example to reveal the effect of CSS on a website. Below you see how the Facebook Webpage looks as usual (with CSS):
And here you see how Facebook looks without CSS:
As we can see, CSS makes a website’s visual presentation much better.
CSS Syntax:
Let’s write our first CSS code. For instance, I would like to change the color of the
Firstly, we need to tell CSS how to find the HTML element. We can do it with a feature called “selector”. A selector in CSS is used to find HTML elements by their tag name, class name, id and much more.
After that, we can declare CSS rules, between brackets of the selector, each ending up with a semi-colon:
So based on the defined selector ( h1), CSS can now understand where to apply the new rules:
There are many different ways to define a CSS selector, below you can see some examples of the selector types:
You can check here for more about CSS Selectors.
How to Add CSS in HTML?
Now you’ve learned why and how to define a selector and write some CSS code. But that’s not enough. We also need to add CSS inside HTML otherwise it doesn’t recognize the changes.
We can add CSS in an HTML file in 3 different ways:
1. External CSS File:
Keeping CSS code in a separate file is best practice. In real programming world, we need to keep HTML, CSS and JavaScript code in separate files and later import them where necessary.
Then we can import index.css to HTML with a tag like below:
So now the HTML file has the CSS code and the changes will apply to the elements.
Learn to style HTML using CSS
Cascading Stylesheets — or CSS — is the first technology you should start learning after HTML. While HTML is used to define the structure and semantics of your content, CSS is used to style it and lay it out. For example, you can use CSS to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.
Looking to become a front-end web developer?
We have put together a course that includes all the essential information you need to work towards your goal.
Prerequisites
You should learn the basics of HTML before attempting any CSS. We recommend that you work through our Introduction to HTML module first.
Once you understand the fundamentals of HTML, we recommend that you learn further HTML and CSS at the same time, moving back and forth between the two topics. This is because HTML is far more interesting and much more fun to learn when you apply CSS, and you can’t learn CSS without knowing HTML.
Before starting this topic, you should also be familiar with using computers and using the web passively (i.e., just looking at it, consuming the content). You should have a basic work environment set up, as detailed in Installing basic software, and understand how to create and manage files, as detailed in Dealing with files — both of which are parts of our Getting started with the web complete beginner’s module.
It is also recommended that you work through Getting started with the web before proceeding with this topic, especially if you are completely new to web development. However, much of what is covered in its CSS basics article is also covered in our CSS first steps module, albeit in a lot more detail.
Modules
This topic contains the following modules, in a suggested order for working through them. You should start with the first one.
CSS (Cascading Style Sheets) is used to style and layout web pages — for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features. This module provides a gentle beginning to your path towards CSS mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to HTML.
This module carries on where CSS first steps left off — now you’ve gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. This module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more.
The aim here is to provide you with a toolkit for writing competent CSS and help you understand all the essential theory, before moving on to more specific disciplines like text styling and CSS layout.
With the basics of the CSS language covered, the next CSS topic for you to concentrate on is styling text — one of the most common things you’ll do with CSS. Here we look at text styling fundamentals, including setting font, boldness, italics, line and letter spacing, drop shadows, and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links.
At this point, we’ve already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it’s time to look at how to place your boxes in the right place with respect to the viewport, and one another. We have covered the necessary prerequisites so we can now dive deep into CSS layout, looking at different display settings, modern layout tools like flexbox, CSS grid, and positioning, and some of the legacy techniques you might still want to know about.
Solving common CSS problems
Use CSS to solve common problems provides links to sections of content explaining how to use CSS to solve very common problems when creating a web page.
From the beginning, you’ll primarily apply colors to HTML elements and their backgrounds; change the size, shape, and position of elements; and add and define borders on elements. But there’s not much you can’t do once you have a solid understanding of even the basics of CSS. One of the best things about learning CSS is that once you know the fundamentals, usually you have a pretty good feel for what can and can’t be done, even if you don’t know how to do it yet!
«CSS is weird»
CSS works a bit differently from most programming languages and design tools you’ll come across. Why does it work the way it does? In the following video, Miriam Suzanne provides a useful explanation of why CSS works as it does, and why it has evolved as it has:
See also
The main entry point for CSS documentation on MDN, where you’ll find detailed reference documentation for all features of the CSS language. Want to know all the values a property can take? This is a good place to go.
Introduction to CSS
CSS is a language for setting the design or appearance of a website’s content. This means any choices of a visual nature, including typography, colors, layout, animation, and all similar concerns are the domain of CSS. HTML isn’t concerned with these things and instead focusses on defining the meaning and structure of the content.
CSS Files
It is possible to write CSS within an HTML document, either in the head in a style element, or in a style attribute directly applied to a specific element. However, neither of these methods are good practices and both ultimately defeat many of the strengths of CSS. Instead, it is best to use a dedicated CSS file that is shared by all HTML pages in a site.
It’s best to use a separate CSS file that is shared by all HTML pages on a site.
To do so, you first create the CSS file. It can be named whatever you want, as long as it has the «.css» file extension. Common names include style.css and main.css. Some developers like to place their CSS file in a subfolder, but there is no particular advantage to doing so.
Syntax
Selectors
CSS is written by first identify which HTML should have particular styles applied. The identifier is called a selector. Selectors can target HTML by element, by class name, or by a number of other, more complex methods. For more information, see the CSS Selectors article. After the selector, a pair of curly braces ( <> ) is wrapped around whatever style code is written to be applied to that selector.
A selector with its curly braces might look like this:
Declarations
The code written inside the curly consists of declarations, also known as rules, which are individual statements of how a particular aspect of style for the selected elements should behave. A declaration is made up of a property—which is the aspect of the design being determined—paired with a value—which is the specific desired behavior for the property being addressed. Properties and values are separated by a colon ( : ) and values are followed by a semi-colon ( ; ) to end the declaration.
A declaration (property / value pair) might look like this:
So when we put it all together, a selector combined with a declaration looks like this:
You can have as many declarations per selector as needed. By convention, usually only one declaration is written per line.
So when we put it all together, a selector combined with a declaration looks like this:
Notice that the declarations are written in alphabetical order by property. This helps keep things organized and makes it easy to find a particular property.
The Cascade
The «C» in «CSS» stands for the cascade, which refers to the way CSS declarations can override other declarations and to the way declarations can be inherited by an element’s decendants.
Order of Declarations
The first important thing to know is that CSS, like the english language, is read from top to bottom. This means that, all other factors being equal, if two declarations conflict with one another, the declaration furthest down the page will be used by the browser. For example:
Generally, whatever declaration comes last is the one that will be used.
Specificity
However, some selectors are stronger than others and can win a conflict regardless of order. The hierarchy of selector strength is called specificity. The more specific an element, the easier it wins in a conflict. For example, a class selector is more specific than an element selector. Let’s see it in action:
In the example above, try changing the color on the h2 selector. Does it have any effect? If you add a different font-weight declaration to both selectors, which one do you think will be honored?
There are too many possible combinations and variations of selectors to explore specificity comprehensively here, but in general things work as you would expect. To explore and test combinations, try this specificity calculator.
Specificity is the reason it is recommended you don’t use IDs as selectors. They are too specific and can cause unintended overrides.
Inheritance
Some CSS properties are passed on to an element’s children, a behavior known as inheritance. (Get it?) For instance, if text-align: center; is applied to an article element, all the children of the article will inherit the property and have centered text.
Only some properties are inherited by an element’s decendants. But they are mostly the ones you would expect.
A paragraph with some text in it. Nice, meaningless text.
Default Styles
Browsers all have a set of default styles which are applied to HTML when no other styles have been provided. Basically, this is built-in CSS. Any CSS that you write serves to override and replace these default styles. Let’s take a look at some HTML without any CSS specified:
A paragraph with some text in it. Nice, meaningless text. La da da da da du dum.
Notice that the headings display larger and bolder than the paragraph, even though no CSS has been explicitly provided. This is because they are using the browser’s default styles. Even the typeface of the text and the white background are all determined by the default styles.
Even though elements have default styles, those styles should not be considered when choosing HTML elements. Elements should be chosen based on meaning.
It’s also important to know that different browsers can have different default styles, so it’s best not to rely upon them too heavily.
Comments in CSS
Sometimes you want to leave notes for yourself or others in your CSS, or you want to mark out sections within a file, or you want to temporarily disable a bit of code while saving it for later. To do this while making sure the browser doesn’t try to read the content as part of the CSS, you must use comments.
Commenting is basically a way to mark text in a code file as not part of the code to be read by the browser.
Comments in CSS are marked at the beginning with a slash then an asterisk ( /* ). They are close with an asterisk followed by a slash ( */ ).
For longer, multi-line comments or comments that serve as section headings in CSS, it is common to use block comments, where the opening and closing lines are filled with equals signs or asterisks:
It’s important to note that comments use different formats in different languages. CSS comments won’t work in HTML and vice-versa.
How CSS is structured
Now that you are beginning to understand the purpose and use of CSS, let’s examine the structure of CSS.
Prerequisites: | Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of How CSS works. |
---|---|
Objective: | To learn CSS’s fundamental syntax structures in detail. |
Applying CSS to HTML
First, let’s examine three methods of applying CSS to a document: with an external stylesheet, with an internal stylesheet, and with inline styles.
External stylesheet
The CSS stylesheet file might look like this:
Internal stylesheet
The HTML for an internal stylesheet might look like this:
In some circumstances, internal stylesheets can be useful. For example, perhaps you’re working with a content management system where you are blocked from modifying external CSS files.
But for sites with more than one page, an internal stylesheet becomes a less efficient way of working. To apply uniform CSS styling to multiple pages using internal stylesheets, you must have an internal stylesheet in every web page that will use the styling. The efficiency penalty carries over to site maintenance too. With CSS in internal stylesheets, there is the risk that even one simple styling change may require edits to multiple web pages.
Inline styles
Inline styles are CSS declarations that affect a single HTML element, contained within a style attribute. The implementation of an inline style in an HTML document might look like this:
Avoid using CSS in this way, when possible. It is the opposite of a best practice. First, it is the least efficient implementation of CSS for maintenance. One styling change might require multiple edits within a single web page. Second, inline CSS also mixes (CSS) presentational code with HTML and content, making everything more difficult to read and understand. Separating code and content makes maintenance easier for all who work on the website.
There are a few circumstances where inline styles are more common. You might have to resort to using inline styles if your working environment is very restrictive. For example, perhaps your CMS only allows you to edit the HTML body. You may also see a lot of inline styles in HTML email to achieve compatibility with as many email clients as possible.
Playing with the CSS in this article
For the exercise that follows, create a folder on your computer. You can name the folder whatever you want. Inside the folder, copy the text below to create two files:
index.html:
styles.css:
When you find CSS that you want to experiment with, replace the HTML contents with some HTML to style, and then add your test CSS code to your CSS file.
As an alternative, you can also use the interactive editor below.
Read on and have fun!
Selectors
A selector targets HTML to apply styles to content. We have already discovered a variety of selectors in the Getting started with CSS tutorial. If CSS is not applying to content as expected, your selector may not match the way you think it should match.
Each CSS rule starts with a selector — or a list of selectors — in order to tell the browser which element or elements the rules should apply to. All the examples below are valid selectors or lists of selectors.
Try creating some CSS rules that use the selectors above. Add HTML to be styled by the selectors. If any of the syntax above is not familiar, try searching MDN.
Note: You will learn more about selectors in the next module: CSS selectors.
Specificity
You may encounter scenarios where two selectors select the same HTML element. Consider the stylesheet below, with a p selector that sets paragraph text to blue. However, there is also a class that sets the text of selected elements to red.
The CSS language has rules to control which selector is stronger in the event of a conflict. These rules are called cascade and specificity. In the code block below, we define two rules for the p selector, but the paragraph text will be blue. This is because the declaration that sets the paragraph text to blue appears later in the stylesheet. Later styles replace conflicting styles that appear earlier in the stylesheet. This is the cascade rule.
However, in the case of our earlier example with the conflict between the class selector and the element selector, the class prevails, rendering the paragraph text red. How can this happen even though a conflicting style appears later in the stylesheet? A class is rated as being more specific, as in having more specificity than the element selector, so it cancels the other conflicting style declaration.
The rules of specificity and the cascade can seem complicated at first. These rules are easier to understand as you become more familiar with CSS. The Cascade and inheritance section in the next module explains this in detail, including how to calculate specificity.
For now, remember that specificity exists. Sometimes, CSS might not apply as you expected because something else in the stylesheet has more specificity. Recognizing that more than one rule could apply to an element is the first step in fixing these kinds of issues.
Properties and values
At its most basic level, CSS consists of two components:
When a property is paired with a value, this pairing is called a CSS declaration. CSS declarations are found within CSS Declaration Blocks. In the example below, highlighting identifies the CSS declaration block.
Finally, CSS declaration blocks are paired with selectors to produce CSS rulesets (or CSS rules). The example below contains two rules: one for the h1 selector and one for the p selector. The colored highlighting identifies the h1 rule.
Setting CSS properties to specific values is the primary way of defining layout and styling for a document. The CSS engine calculates which declarations apply to every single element of a page.
CSS properties and values are case-insensitive. The property and value in a property-value pair are separated by a colon ( : ).
Look up different values of properties listed below. Write CSS rules that apply styling to different HTML elements:
Warning: If a property is unknown, or if a value is not valid for a given property, the declaration is processed as invalid. It is completely ignored by the browser’s CSS engine.
Functions
While most values are relatively simple keywords or numeric values, there are some values that take the form of a function.
The calc() function
An example would be the calc() function, which can do simple math within CSS:
This renders as:
A function consists of the function name, and parentheses to enclose the values for the function. In the case of the calc() example above, the values define the width of this box to be 90% of the containing block width, minus 30 pixels. The result of the calculation isn’t something that can be computed in advance and entered as a static value.
Transform functions
The output from the above code looks like this:
Look up different values of properties listed below. Write CSS rules that apply styling to different HTML elements:
@rules
CSS @rules (pronounced «at-rules») provide instruction for what CSS should perform or how it should behave. Some @rules are simple with just a keyword and a value. For example, @import imports a stylesheet into another CSS stylesheet:
In the example below, the stylesheet defines a default pink background for the element. However, a media query follows that defines a blue background if the browser viewport is wider than 30em.
You will encounter other @rules throughout these tutorials.
See if you can add a media query that changes styles based on the viewport width. Change the width of your browser window to see the result.
Shorthands
For example, this one line of code:
is equivalent to these four lines of code:
is equivalent to these five lines:
Later in the course, you will encounter many other examples of shorthand properties. MDN’s CSS reference is a good resource for more information about any shorthand property.
Try using the declarations (above) in your own CSS exercise to become more familiar with how it works. You can also experiment with different values.
Warning: One less obvious aspect of using CSS shorthand is how omitted values reset. A value not specified in CSS shorthand reverts to its initial value. This means an omission in CSS shorthand can override previously set values.
Comments
As with any coding work, it is best practice to write comments along with CSS. This helps you to remember how the code works as you come back later for fixes or enhancement. It also helps others understand the code.
Add comments to your CSS.
White space
White space means actual spaces, tabs and new lines. Just as browsers ignore white space in HTML, browsers ignore white space inside CSS. The value of white space is how it can improve readability.
In the example below, each declaration (and rule start/end) has its own line. This is arguably a good way to write CSS. It makes it easier to maintain and understand CSS.
The next example shows the equivalent CSS in a more compressed format. Although the two examples work the same, the one below is more difficult to read.
For your own projects, you will format your code according to personal preference. For team projects, you may find that a team or project has its own style guide.
Warning: Though white space separates values in CSS declarations, property names never have white space.
For example, these declarations are valid CSS:
But these declarations are invalid:
You should always make sure to separate distinct values from one another by at least one space. Keep property names and property values together as single unbroken strings.
To find out how spacing can break CSS, try playing with spacing inside your test CSS.
Summary
At this point, you should have a better idea about how CSS is structured. It’s also useful to understand how the browser uses HTML and CSS to display a webpage. The next article, How CSS works, explains the process.
Best way to include CSS? Why use @import?
to the head of the document?
18 Answers 18
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
From a page speed standpoint, @import from a CSS file should almost never be used, as it can prevent stylesheets from being downloaded concurrently. For instance, if stylesheet A contains the text:
There are occasionally situations where @import is appropriate, but they are generally the exception, not the rule.
(2022 Update: I should note that, many professional developers now manage their CSS with a system like SASS, or frameworks compatible with React, either of which would handle these optimizations internally.)
I’m going to play devil’s advocate, because I hate it when people agree too much.
1. If you need a stylesheet that depends on another one, use @import. Do the optimization in a separate step.
If you have one stylesheet that depends on another, the most logical thing to do is to put them in two separate files and use @import. That will make the most logical sense to the next person who looks at the code.
(When would such a dependency happen? It’s pretty rare, in my opinion
usually one stylesheet is enough. However, there are some logical places to put things in different CSS files:)
Theming: If you have different color schemes or themes for the same page, they may share some, but not all components.
Python uses import; C uses include; JavaScript has require. CSS has import; when you need it, use it!
2. Once you get to the point where the site needs to scale, concatenate all the CSS.
Before the site reaches production scale though, it’s more important that the code is organized and logical, than that it goes slightly faster.
It is best to NOT use @import to include CSS in a page for speed reasons. See this excellent article to learn why not: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/
Also it is often harder to minify and combine css files that are served via the @import tag, because minify scripts cannot «peel out» the @import lines from other css files. When you include them as
using the link method, the stylesheets are loaded parallel (faster and better), and nearly all browsers support link
import loads any extra css files one-by-one (slower), and could give you Flash Of Unstyled Content
@Nebo Iznad Mišo Grgur
The following are all correct ways to use @import
Yes, always use @import and external Cascading Style Sheets in your Website!
(There has been a lot of false information posted on the web the past 10 years about the use of @import I intend to correct. So please read my information carefully below.)
Rule Number One
Never Rely on JavaScript API’s or Tricks to Manage Cascading Style Sheets!! Do NOT rely on 3rd party vendor CSS solutions! Never use SASS, React, Modernizr, Bootstrap, or Angular to manage CSS. I know, I have used them all. Always manage Cascading Style Sheets yourself using hand-written CSS text files and your site will not only run faster, but you will have total control over your websites design and your user experience. If you rely on these poorly designed systems they will fail in numerous scenarios, slow down your site, and fail in numerous versions of older browsers. too many to count.
Rule Number Two
Rule Number Three
Use of @import in your CSS does NOT slow down page load or parsing. Multiple @imports combined in an embedded
The ONLY time @import does have issues is the following limited scenarios: