CSS is short for Cascading Style Sheets. We use CSS to add styling to webpages. Without it they would look very dull (and likely not be very useful).
CSS introduces the concept of rules, selectors and properties. A rule is a set of properties that apply to a set of elements selected by a selector. Using these concepts, we can selectively style elements on our page. Let’s see an example of simple CSS rule:
.humongous
is what we call a class selector. It “selects” all elements from the DOM with humongous
set as their classname
attribute.
Within the curly braces are the properties that will be applied to elements selected by the selector.
In this case, we set the font size to 100px
.
We can also select elements by their id
attribute by using the ID selector.
The following would set the text color of the element with id = "dabadee"
:
We can also select by generic attributes:
We can also “nest” selectors to apply styling to children of selectors.
The following would set the height and width of all (that is what *
means) children of the element with id = "the-answer"
:
There are way more properties and selectors than we have time to cover here. MDN has some great documentation available which can be used both for learning and as a reference.
Using CSS
Let’s use CSS to add some styling to our page. Our page would look a lot better if we added some background and a box containing the form for submitting guesses. We probably also want to center the box on the page.
To make the styling a bit easier, add two div elements surrounding the form like this:
The #container
div will be the box that is centered on the page and displays the form.
The #wrapper
element will help with centering of the #container
div.
The simplest way to add CSS to our page is by introducing a style
element in the header of our page like so:
Let’s start by making the page itself fill all the available space. Add the following rule to the styles:
Now, expand the #wrapper
div to fill the entire page and add the background:
Next, fix the dimensions of the #container
element and add a white background to it so that we can distinguish it from the wrapper background.
Let’s also add some space between the elements of the container and the border by using the padding
property.
Some shadow would probably also look nice. Add the following rule:
Great! Now we just need to center the container. There are several ways to accomplish this. I find that the easiest way is often to add the following to the parent element:
The final page should look like this:
If we open it in the browser, we see the following:
Definitely better than before.
CSS Documentation
The MDN Web Docs is a great source of documentation.