Web Design/CSS Classes
What are Classes in CSS?
- Let's say you want to give an HTML element multiple looks with CSS.
- Say for example, sometimes you want the font to be small and white with a black background, while other times you would prefer the font to be big and blue with a light blue background. CSS allows you to do this with the use of classes.
- The name of the actual class can be called whatever you wish!
To make a class, in between <style> & </style> type the name of the class following the tag name.
<style> p.first { color: blue; } </style>
Then in the HTML tag add the class
<p class="first">This is some text</p>
The last code will set the text color to blue for all of the 'p' elements with a class value of 'first'. It's also possible to apply the desired style to all of the elements with an specific class value no matter which element the class attribute is at. To do that, the '*' character is used.
<style> *.first { color: blue; } </style>
Example 1
The code below should make the:
- Paragraph with the first class, appear as blue color.
- Paragraph with the Second class, appear as red color.
- Paragraph with the no class, appear as normal.
Type the code below into your code editor and save the file as cssclass.html
<html> <head> <style type = "text/css"> p.first{ color: blue; } p.second{ color: red; } </style> </head> <body> <p>This is a normal paragraph.</p> <p class="first">This is a paragraph that uses the p.first CSS code!</p> <p class="second">This is a paragraph that uses the p.second CSS code!</p>
Example 2
The code below should make the:
- Heading2 appear red with font size of 20px.
- Paragraph with the firstpara class, appear as gray color.
- Paragraph with the Secondpara class, appear as red color.
- Paragraph with the Thirdpara class, appear as white text with purple background.
- Paragraph with the no class, appear as normal.
Type the code below into your code editor and save the file as cssclass2.html
<html> <head> <style> h2 { color: red; font-size: 20px; } p.firstpara { background-color: gray; } p.secondpara { background-color: red; } p.thirdpara { background: purple; color: white; } </style> </head> <body> <h2>CSS Classes</h2> <p class="firstpara">This is the p.firstpara paragraph</p> <p class="secondpara">This is the p.secondpara paragraph</p> <p class="thirdpara">This is the p.thirdpara paragraph</p> <p>This has no CSS formatting</p> </body> </html>
References