Graduate Program KB

CSS For Javascript


Module 1

Refresher

Properties in CSS are the attributes which we can specify values for like 'color' or 'font-size'. A selector is a descriptor which lets you target specific elements on the page. A declaration is a combination of a property and a value. A rule/style is a collection of selectors.

Media Queries

In order to accommodate screens of different shapes and sizes, CSS features media queries, which allows us to apply different CSS in different scenarios. This is because responsive design is so important in front-end development. Media queries use the '@media' syntax. This can be thought of similar to an if statement in JS. Example:

@media (condition) {
  /* Some CSS to be run if the condition is true */
}

Or similarly, we can show something different when the condition becomes true. Display: none will hide an element. It is important to note that not all CSS properties have corresponding media features.

Pseudo-Classes

These lets us apply a chunk of CSS based on an elements current state. An example may be changing the colour of text when it is hovered over. :hover is the pseudo class used to achieve this effect. :focus is another class which applies a style when an interactive element has focus (clicking on a button for example). :checked applies only to checkboxes that are 'filled-in'. So for "input type='SomeName'", we would have a matching:

<style>
Input: checked {
  width: 24px;
  height: 24px;
}
</style>

There are also pseudo-classes that can help to apply conditional logic. These include :last-child, :first-child etc. Additionally there is :first-of-type and :last-of-type.

Pseudo-Elements

Like pseudo-classes, however they don't target a specific state. Instead they target sub-elements, within an element.

<style>
    input {
        font-size: 1rem;
    }
    input::placeholder {
        color: goldenrod;
    }
</style>

<label>
    Postal Code
    <input
        type="text"
        placeholder="A1A 1A1"
        />
</label>

With regard to syntax, the pseudo-elements use two colons instead of one. The two most common pseudo-elements are ::before and ::after.

Combinators

Say we wanted to style only navigation links. This can be done with a combinator.

<p>Hello, <a>this</a> is a sentence!</p>
<nav>
  <a> This is a link </a>
  <a> This is also a link </a>
</nav>
nav a {
  color: red;
}

This example when we use 'nav a' will make only the a tags nested within nav the color red. The a tag within the p tag will remain as its default question. We could also use ">" between the two elements within style, to reference only the direct child of the LHS, rather than everything within it.

Colour

Many developers choose to adjust text colour of a specific element using hex code. HSL is another method and stands for hue, saturation, and lightness. HSL can be implemented anywhere that hex code normally would be found. The first parameter is the deg suffix (as it is measured in degrees), and the other two following are percentages. Alpha can also be added onto the end, which specifies how visible a colour is, with numbers approaching 1 becoming more visible, and approaching 0 becoming less visible.

Units

The most popular unit for size is the pixel. They correspond (more or less) to what we see on the screen. 'em' is a relative unit, which is equal to the font-size of the current element. For example, a heading with font-size 32px, with a bottom-padding of 2em, would actually have a bottom-padding of (2*32 = 64). What is more commonly used is 'rem'. Rem is directly relative to the root, rather than the current element. By default the root element, the html tag has a font-size of 16px.

Text-Formatting

Bold, italics and underline are the 3 most common formatting options in CSS.

.element {
  font-weight: bold;
  font-weight: italic;
  text-decoration: underline;
}

We can use the numbering system (from 0 to 1000) to more precisely specify the font weight. (Bold maps to 700, and the default value is 400). As shown we can also make the element be italic. And finally, we can toggle an element's underline with the text-decoration property.

Alignment

Sometimes we want to tweak text alignment. To shift characters horizontally, we can use the text-align property. Using left, right, or middle, will shift where a paragraph aligns to.

Text-Transformations

text-transform: uppercase; /* Render in all caps */
text-transform: capitalize; /* Capitalize the start of each word */

But why not just type it out the correct way and get rid of the CSS? Because, we may wish to change our minds later, and it is far easier to remove just one line of css.

Spacing

letter-spacing: 3px; /*Used to change the horizontal spacing between characters.*/
line-height: 1.5; /* Standard height*/

Line height tweaks the vertical distance between lines. Line-height is odd as it takes a number, and multiplies the font-size to determine the correct height. To comply with accessibility guidelines, body text should have a minimum line-height of 1.5.

Rendering Logic

HTML tags add some minimal style be default. The a tag already has colour, changes the cursor on hover, and has an underline by default. These styles are part of user-agent stylesheets. Mostly, browsers come up with their own default styles.

Inheritance

Certain CSS properties inherit from their parents. Not all properties are inheritable however. And sometimes we want a property to inherit even when it normally wouldn't do so. (Like the a tag with its blue colour). We can use the example below to make the tag inherit it's parents colour.

a {
  color: inherit;
}

The Cascade

p {
  font-weight: bold;
  color: hsl(0deg, 0%, 10%);
}
.introduction {
  color: violet;
}

Assuming that introduction is a className given to a paragraph, it is clear that we have given two conflicting values of colour to the same paragraph. But which 'wins' the battle. The paragraph will be both bold and violet (taking elements from each). The more specific selector will always win, as they are merged in later therefore overwriting anything conflicting which came before. The paragraph initially has its hsl colour, which is then overwritten by the more specific className selector, which specifies the colour should be violet.

Block and Inline

The web was built for displaying inter-linked documents. A written sheet of paper can be used as an example. Pages are constructed of blocks, placed on each other. New paragraphs are inserted below the previous block element. English documents have two directions: the page consists of vertically-oriented blocks which are made from horizontally-oriented words. CSS is based on this. It has block direction (vertical), and inline direction (horizontal).

The Box Model

Winter Layers

The four aspects which make up the box model are content, padding, border and margin. A helpful analogy is that of a person on a winter walk. The content is the person themselves, the human inside the coat. The padding is the polyester stuffing in the coat (more stuffing = more 'poofed-up' coat). The border is the material of the coat, it has both thickness and colour, this will affect the persons appearance. The margin is the 'personal space'. The distance between us and other people/objects.

Box-Sizing

Box sizing in browsers can operate different to what we would expect. If we had a section of width: 150px; and a p with width: 100%; padding: 16px; border 2px solid;. The actual size of the box would be 186px wide rather than the 150 specified. This is because padding and border are applied on top of the width, on both the top and bottom. We can use "box-sizing: border-box" in our css for the p tag to be able to set a constraint of 150px max. The padding and border will still be applied, but the width will be 150px total (so the content may be squished inside).
Instead of having to swap box-sizing on every layout element We can set it as the default value for all elements like below:

*,
*::before,
*::after {
  box-sizing: border-box;
}

Padding

Padding can be thought of as inner space. A background colour applied to an element would also be applied to the surrounding padding. Padding can be set for all directions at once, or specified for individual directions. Px, em, and rem can all be used to specify padding size. Pixels are thought to be the best to use for padding, unlike for font-size. We can also use percentages for padding; however they are based on the element's available width. Sometimes this can be useful.
Shorthand can be used for padding.

.box {
  padding: 15px 30px;
  padding: 15px 30px 15px 30px; /* These two are both equal*/
}

When two values are passed like the first line, the first value is used for both vertical directions, and the second for both horizontal. Or we can directly pass 4 values like the second row in order top, right, bottom and left (clockwise direction starting at 12). This shorthand pattern can also be used for some other CSS properties.

Border and Outlines

Border is different to margin and padding in that it has a visual element.

.box {
  border: 3px solid black;
  border-radius: 0px 0px 50px 25px;
}

As shown above, border takes three specific styles, in order these are the border width, border style and border colour. The only required field is actually the border-style as the other two can default to other values. Border-radius is a property which can round an element (even if it has no border). It accepts discrete values in each direction. Percentages can also be used. Border will affect layout, but outline (which is similar) will not.

Margin

Margin increases the space around an element, remember our person with a coat analogy from before. The syntax is very similar to that of padding, with shorthand also able to be used. Padding and border only accept positive numbers, however margin can accept a negative number which pulls an element outside of its parent. Margin is all about changing the gap between elements. Negative margins shrink the gap between these elements. Negative margins can affect the position of all siblings. Imagine 3 elements in block (vertically stacked), if the first element had a negative top-margin, all three blocks would be pulled up equally.

.box {
  height: 200px
  width: 300px
  margin-left: auto;
  margin-right: auto;

}

Using margin-left: auto; and the same for right will centre an element. Auto seeks to use the maximum available space. It works the same way for the width property. This only works for horizontal margin. It only works on elements with an explicit width. Block elements naturally grow to fill the available horizontal space, so we need to give our element width to centre it.

Flow Layout

Each HTML elements will have its layout calculated by a layout algorithm. These are known as layout modes, and there are 7 distinct ones. For now, lets just focus on one known as flow layout. This is the default. Flow layout can be called the Microsoft word layout as its intended to be used for document type layouts. The two main elements types in this layout are block elements (headings, paragraphs, footers etc.) and inline elements (links, string of bold text etc.). Each HTML element has a default type. div and header are block, span and a are inline. We can toggle a particular element with the display property. Display: block; for example.

Inline elements are hard to move. You can push it around with margin-left and right as this works in the inline direction, but you cannot give it width or height. Block elements when placed greedily expand to fill the entire horizontal space that is available. Width: fit-content; can be used to shrink a block element down to the minimum size required. Regardless, the block element will not share any inline space, even if there is plenty left.

Inline has magic space occasionally. For example, an embedded image with 300px in height, may have a parent element and total takes up 306px of space without margin, padding etc. This is because the browser treats inline elements as if they are all typography, so that lines in a paragraph are not too tightly packed. Display: block; can be used on images to remove this effect, or line-height: 0; for the wrapping (parent) div.

Whitespace between inline images can also occur. This is caused by the whitespace between HTML elements. Remove this from HTML to have images directly touching. Inline elements can line-wrap. Obviously an a tag can be longer than one line, and therefore will wrap.

Display: Inline-Block

This can be used to place a block-level element within an inline-context. The layout treats it as an inline element, but internally it acts more like a block element. Using inline-block allows us to use the full suite of CSS styles on our block element. It is important to note however, that inline-block doesn't wrap.

Width Algorithms and Keyword Values

When we use percentage-based widths, the percentages are based on the parent element's content space. If a body tag takes 400px of space, the child with 100% width will take 400px of body space. Combined with 32px of margin, and the element will be partially off the page. The two kinds of values we can specify for width are measurements and keywords. Measurement based are either completely explicitly or relative to the available space. Keywords on the other hand are dependant on the context. Width: min-content;, is a way to specify that we want out element to become as narrow as possible, based on the child contents. This is known as an intrinsic value, while measurements and auto are known as extrinsic. Max-content follows the same principles, but never adds any line breaks. The elements width will be the smallest value which contains ALL the content. A paragraph would be only on one very long line. Fit-content is the middle child, if the width can fit within the parent container size then it does, if not it will add a line break as needed to never take up too much space. Works similar to width: auto;. Min and max widths can also be applied. These specify how small or large an element possible can be. It will not go past these upper and lower bounds, which is helpful when text may be resized due to different devices screen size.

Height Algorithms

Height is typically more dynamic than width. We want our design to work whether it has 20 words or 20,000. And for pages with the same content, we would want containers to grow taller on phone screens and shorter on desktop screens. We typically avoid setting a fixed height. We sometimes wish to apply a minimum height however, especially to the wrapper around our entire page. We want to make sure our apps content is at least the height of the window. But because body doesn't have a specific height set, and attempts to stay as small as possible whilst still containing all its children, setting height of a child to 100% will not work. To fix this we can either put height: 100% on every element before our main one (including html and body), and then put min-height: 100% on our main wrapper. HTML when given height: 100% takes up 100% of the viewport. It is important to remember that by default width looks up the tree, and height looks down the tree.

Margin Collapse

Earlier we had the example of someone with a jacket walking around. And margin referred to the space between the person, and other people or objects (their personal space). Sometimes margins will overlap or combine. For example, during covid you had to keep 6ft of distance between yourself and others. You may have a 6ft radius, and other person may have their 6ft radius, but when you come close together, you do not need to have a 12ft radius from each other. Some rules of margin collapse are as follows.

  1. Only vertical margins collapse. If paragraphs had 24px of margin both top and bottom. They would still only be 24px apart rather than 48px. They overlap. Horizontal margins do not overlap.

  2. Margins only collapse in flow layout. If you have children inside a display: flex; parent, those children's margins will never collapse.

  3. Only adjacent elements collapse. br is often used to signify a line-break. Using our example from the first rule, the paragraphs would now be 48px apart, as they are no longer adjacent, and no longer overlap.

  4. If margins are asymmetrical, the larger margins wins when collapsing (i.e. margin will be set to the larger of the two).

  5. Nesting doesn't prevent collapsing. A p within a div will still collapse its margins with the next adjacent non-nested element.

Margin is meant to increase the distance between siblings, not increase the gap between child and parent (this is what padding is used for). Because margins only collapse when they are touching, padding or border can be used, and it will prevent margin collapsing. A scroll container will also stop collapsing.

Margins can also collapse in the same direction. A negative margin will pull an element in the opposite direction, so a sibling with one such margin may overlap its neighbour. The more-negative margin takes priority in collapsing. With an adjacent negative and positive margin, they are added together to find the collapsed margin.