What are advantages of using CSS? Why we need to separate CSS from HTML?

CSS is a style sheet language used to set the visual style of web pages. Along with HTML, it is used in modern web development to create web pages and user interfaces for web applications. But it is important to separate CSS (visual presentation of content) from HTML (description of content).

Advantages of CSS

  • Code reuse. For example, you have three web pages, which have big green "Save" button. Instead of stylizing them with "color" HTML attribute three times (for each page), you can define one CSS rule, which will set color and other visual attributes for all three buttons.
  • As a result, pages load faster. Less code means faster download times.

  • As another result, easier to maintain and update. To change the visual style of an element across the whole site, you only have to make an edit in one place.

  • Cleaner HTML. HTML code, which is not polluted with stylization attributes is more readable and easier to understand both for humans and machines.

  • Viewing options. CSS can help you to make available your website for different media by allowing the same markup page to be presented in different viewing styles — for example, you may create a separate stylesheet for print or for a mobile device.

  • A lot of formatting options. With latest CSS version you can do a lot of amazing things and implement very rich UI for your web application.

Why to separate CSS from HTML?

The key point is separation of concerns. In software development, it is a design principle for separating a program code into distinct areas, such that each area of code addresses a separate concern. Learn more about importance of separation of concerns principle here.

Usually, separation of CSS from HTML means putting all CSS rules into separate file. Ideally, HTML should not contain any CSS styles, rules or style attributes. Separation is necessary for readability and maintainability. It's definitely easier to just open the file that contains CSS rules instead of searching style attributes in huge HTML file. It also allows us to change whole style of page by changing CSS file attached to it, but in some cases it is not possible without changing HTML, some coupling in your front-end code is inevitable.. As well, you can use one CSS style sheet across different pages or even different websites. Another advantage of moving CSS styles to separate file is cacheability. Browsers can cache style sheet file on client side, thus saving bandwidth and reducing loading time.

Short answer

  • There is a lot of advantages which were introduced to web development with invention of CSS: code reuse, readability, maintainability, performance, powerful tools for stylization.
  • It is always good to separate your CSS styles from HTML into separate file.

Similar articles

Comments