There are multiple ways to write CSS for your website and the method you choose may vary depending on your chosen CMS or framework, but essentially it boils down to one of the following methods.
Inline styles are added directly to the element which they are to be applied to.
<p style="background-color: indianred; color: palegoldenrod; padding: 10px;">Some paragraph text</p>
which would render as
Some paragraph text
Because the styles are applied directly to an element, they do not impact any other elements on the page, so this particular styling will not apply to any other
<p> elements on the page.
<p style="background-color: indianred; color: palegoldenrod; padding: 10px;">A styled paragraph</p>
<p>An unstyled paragraph</p>
- Styles are scoped only to the element they are applied to so there are no cascading issues.
- All the styles are contained within the HTML file so only one request needs to be made to the server to fetch your page.
- Managing a large code base is virtually impossible
- HTML markup becomes bloated
<style> tag is used to define styling information for a HTML document.
It’s recommended to place the
<style> tag in the
<head> section of your HTML.
The above inline style translated into a
<style> tag would look like this.
The key difference here is that the styling now applies to all
<p> tags on the page. This is where the cascading (the ‘C’ in CSS) comes into play.
- Styles are all defined in a single place making them easier to find and manage
- Still only one request needs to be made to the server to fetch your page.
- HTML markup becomes cleaner
- Styles are available only to the page on which the
<style>tag is present.
A linked stylesheet would contain your css declarations in a separate file and be linked in the
<head> section of your HTML like this.
<link src="/path/to-your/stylesheet.css" type="text/css" rel="stylesheet" />
We can now move all the css declarations from the
<style> tag to an external stylesheet which would look like this.
As with the
<style> tag, cascading rules also apply when using linked stylesheets.
- Styles are fully separated from markup
- A single stylesheet can be linked to multiple pages of your website
- The server now needs to make two requests — one for the
.htmlfile and one for the
So which method should you use? Of course, as with most things, it depends.
While all three methods have their benefits and drawbacks, a lot can be said about having styles de-coupled from markup, so having your CSS in a linked stylesheet is the approach I would recommend.
However, sometimes you need to apply some additional inline styling to override specificity on a particular element.
What is your method for adding CSS to your website?