CSS
CSS
You can use the <link> element to link HTML and CSS files together.
The <link> element must be placed within the head of the
HTML file. It is a self-closing tag and requires the following
attributes:
<link
href='https://www.codecademy.com/stylesheets/style.css'
rel='stylesheet'>
Note that in the example above, the path to the stylesheet is a URL:
SELECTORS
Universal
* {
font-family: Verdana;
}
Class
<p class='brand'>Sole Shoe Company</p>
To select this element using CSS, we can create a ruleset with a class
selector of .brand.
.brand {
}
Multiple Classes
.green {
color: green;
}
.bold {
font-weight: bold;
}
Then, you could include both of these classes on one HTML element
like this:
text-transform: uppercase;
Checkpoint 3 Passed
ID
If an HTML element needs to be styled uniquely, we can give it an ID
using the id attribute.
#large-title {
}
Attribute
You may remember that some HTML elements use attributes to add
extra detail or functionality to the element. Some familiar attributes
may be href and src,
[href]{
color: magenta;
}
And it can get more granular from there by adding type and/or
attribute values. One way is by using type[attribute*=value]. In
short, this code selects an element where the attribute
contains any instance of the specified value.
<img src='/images/seasons/cold/winter.jpg'>
<img src='/images/seasons/warm/summer.jpg'>
img[src*='winter'] {
height: 50px;
}
img[src*='summer'] {
height: 100px;
NOTA: To use the attribute selector to select the <a> element with
an href attribute value containing ‘florence’, add the following code
to style.css:
a[href*='florence'] {
color: lightgreen;
}
Pseudo-class
p:hover {
background-color: lime;
}
In the above code, whenever the mouse hovers over a
paragraph element, that paragraph will have a lime-colored
background.
Specificity
Specificity is the order by which the browser decides which CSS styles
will be displayed.
.headline {
color: firebrick;
}
Over time, as files grow with code, many elements may have IDs, which can make CSS
difficult to edit since a new, more specific style must be created to change the style of an
element.
To make styles easy to edit, it’s best to style with a type
selector, if possible. If not, add a class selector. If that is not
specific enough, then consider using an ID selector.
Chaining
h1.special {
}
The code above would select only the <h1> elements with a
class of special. If a <p> element also had a class of special, the
rule in the example would not style the paragraph.
Descendant Combinator
<ul class='main-list'>
<li> ... </li>
<li> ... </li>
<li> ... </li>
</ul>
The nested <li> elements are descendants of the <ul> element and
can be selected with the descendant combinator like so:
.main-list li {
p {
color: blue;
}
.main p {
color: red;
}
Both of these CSS rules define what a <p> element should look
like. Since .main p has a class and a p type as its selector, only
the <p> elements inside the .main element will appear red. This
occurs despite there being another more general rule that
states <p> elements should be blue.
Multiple Selectors
In order to make CSS more concise, it’s possible to add CSS styles to
multiple CSS selectors all at once. This prevents writing repetitive
code.
h1 {
font-family: Georgia;
}
.menu {
font-family: Georgia;}
h1,
.menu {
font-family: Georgia;
}
VISUAL RULES
Font Family
h1 {
font-family: Garamond;
}
When setting typefaces on a web page, keep the following points in
mind:
When the name of a typeface consists of more than one word,
it’s a best practice to enclose the typeface’s name in quotes,
like so:
h1 {
font-family: 'Courier New';
}
Font Size
p {
font-size: 18px;
}
Font Weight
p {
font-weight: bold;
}
Text Align
The text-align property will align text to the element that holds it,
otherwise known as its parent.
h1 {
text-align: right;
}
h1 {
color: red;
background-color: blue;
}
Opacity
Opacity can be used to make elements fade into others for a nice
overlay effect.
.overlay {
opacity: 0.5;
}
In the example above, the .overlay element would be 50%
visible, letting whatever is positioned behind it show through.
Background Image
One option is to make the background of an element an image. This is
done through the CSS property background-image. Its syntax looks
like this:
.main-banner {
background-image:
url('https://www.example.com/image.jpg');
}
.main-banner {
background-image: url('images/mountains.jpg');
}
Important
!important can be applied to specific declarations, instead of full rules.
It will override any style no matter how specific it is. As a result, it
should almost never be used. Once !important is used, it is very hard
to override.
p {
color: blue !important;
}
.main p {
color: red;
}
1. width and height: The width and height of the content area.
2. padding: The amount of space between the content area and the
border.
3. border: The thickness and style of the border surrounding the
content area and padding.
4. margin: The amount of space between the border and the
outside edge of the element.
An element’s content has two dimensions: a height and a width. By default, the
dimensions of an HTML box are set to hold the raw contents of the box.
The CSS height and width properties can be used to modify these default dimensions.
p {
height: 80px;
width: 240px;
}
Pixels allow you to set the exact size of an element’s box (width and height). When
the width and height of an element are set in pixels, it will be the same size on all
devices — an element that fills a laptop screen will overflow a mobile screen.
Borders
A border is a line that surrounds an element, like a frame around a
painting. Borders can be set with a specific width, style, and color:
p {
border: 3px solid coral;
}
The default border is medium none color, where color is the current
color of the element. If width, style, or color are not set in the
CSS file, the web browser assigns the default value for that
property.
p.content-header {
height: 80px;
width: 240px;
border: solid coral;
}
Border Radius
div.container {
border: 3px solid blue;
border-radius: 5px;
}
The code in the example above will set all four corners of the border
to a radius of 5 pixels (i.e. the same curvature that a circle with a
radius of 5 pixels would have).
You can create a border that is a perfect circle by first
creating an element with the same width and height, and
then setting the radius equal to half the width of the box,
which is 50%.
div.container {
height: 60px;
width: 60px;
border: 3px solid blue;
border-radius: 50%;
}
The code in the example above creates a <div> that is a perfect circle.
Padding
The space between the contents of a box and the borders of a box is
known as padding. Padding is like the space between a picture and
the frame
p.content-header {
border: 3px solid coral;
padding: 10px;
}
The code in this example puts 10 pixels of space between the content
of the paragraph (the text) and the borders, on all four sides.
padding-top
padding-right
padding-bottom
padding-left
Each property affects the padding on only one side of the box’s
content, giving you more flexibility in customization.
p.content-header {
border: 3px solid fuchsia;
padding-bottom: 10px;
}
In the example above, only the bottom side of the paragraph’s
content will have a padding of 10 pixels.
Padding Shorthand
Another implementation of the padding property lets you specify
exactly how much padding there should be on each side.
4 Values
p.content-header {
padding: 6px 11px 4px 9px;
}
Correspond to the amount of padding on each side, in a
clockwise rotation. In order, it specifies the padding-top value ( 6px),
the padding-right value (11px), the padding-bottom value ( 4px), and
the padding-left value (9px) of the content.
3 Values
p.content-header {
padding: 5px 10px 20px;
}
The first value sets the padding-top value ( 5px), the second value sets
the padding-left and padding-right values ( 10px), and the third value
sets the padding-bottom value (20px).
2 Values
p.content-header {
padding: 5px 10px;
}
The first value sets the padding-top and padding-bottom values ( 5px),
and the second value sets the padding-left and padding-right values
(10px).
Margin
p {
border: 1px solid aquamarine;
margin: 20px;
}
The code in the example above will place 20 pixels of space on the
outside of the paragraph’s box on all four sides. This means that other
HTML elements on the page cannot come within 20 pixels of the
paragraph’s border.
The amount of margin on each side of a box, you can use the
following properties:
margin-top-margin-right-margin-bottom-margin-left
Each property affects the margin on only one side of the box,
providing more flexibility in customization.
p {
border: 3px solid DarkSlateGrey;
margin-right: 15px;
}
In the example above, only the right side of the paragraph’s box will
have a margin of 15 pixels.
Margin Shorthand
4 Values
p {
margin: 6px 10px 5px 12px;
}
The amount of padding on each side, in a clockwise rotation. In order,
it specifies the margin-top value (6px), the margin-right value (10px),
the margin-bottom value (5px), and the margin-left value ( 12px) of the
content.
3 Values
p {
margin: 5px 12px 4px;
}
The first value sets the margin-top value ( 5px), the second value sets
the margin-left and margin-right values ( 12px), and the third value sets
the margin-bottom value (4px).
2 Values
p {
margin: 20px 10px;
}
The first value sets the margin-top and margin-bottom values ( 20px),
and the second value sets the margin-left and margin-right values
(10px).
Auto
The margin property also lets you center content. However, you must
follow a few syntax requirements. Take a look at the following
example:
div.headline {
width: 400px;
margin: 0 auto;
}
In the example above, the width of the div is set to 400 pixels, which
is less than the width of most screens. This will cause the div to
center within a containing element that is greater than 400 pixels
wide.
min-width—max-width—
p {
min-width: 300px;
max-width: 600px;
}
In the example above, the width of all paragraphs will not shrink
below 300 pixels, nor will the width exceed 600 pixels.
You can also limit the minimum and maximum height of an element:
min-height —max-height —
p {
min-height: 150px;
max-height: 300px;
}
In the example above, the height of all paragraphs will not shrink
below 150 pixels and the height will not exceed 300 pixels.
Overflow
All of the components of the box model comprise an element’s size.
For example, an image that has the following dimensions is 364 pixels
wide and 244 pixels tall.
How can we ensure that we can view all of an element that is larger
than its parent’s containing area?
p {
overflow: scroll;
}
In the example above, if any of the paragraph content overflows
(perhaps a user resizes their browser window), a scrollbar will appear
so that users can view the rest of the content.
Resetting Defaults
All major web browsers have a default stylesheet they use in the
absence of an external stylesheet.
* {
margin: 0;
padding: 0;
}
The code in the example above resets the default margin and
padding values of all HTML elements. It is often the first CSS rule in an
external stylesheet.
Visibility
<ul>
<li>Explore</li>
<li>Connect</li>
<li class="future">Donate</li>
</ul>
.future {
visibility: hidden;
}
In the example above, the list item with a class of future will be
hidden from view in the browser.
Keep in mind, however, that users can still view the contents
of the list item (e.g., Donate) by viewing the source code in
their browser. Furthermore, the web page will only hide the
contents of the element. It will still leave an empty space
where the element is intended to display.
Fortunately, we can reset the entire box model and specify a new
one: border-box.
* {
box-sizing: border-box;
}
The code in the example above resets the box model to border-box for
all HTML elements. This new box model avoids the dimensional issues
that exist in the former box model you learned about.
In this box model, the height and width of the box will remain fixed.
The border thickness and padding will be included inside of the box,
which means the overall dimensions of the box do not change.
<h1>Hello World</h1>
* {
box-sizing: border-box;
}
h1 {
border: 1px solid black;
height: 200px;
width: 300px;
padding: 10px;
}
In the example above, the height of the box would remain at 200
pixels and the width would remain at 300 pixels. The border thickness
and padding would remain entirely inside of the box.
DISPLAY AND POSITIONING
Position
Position: Relative
.green-box {
background-color: green;
position: relative;
}
It’s important to note that offset properties will not work if the
element’s position property is the default static.
.green-box {
background-color: green;
position: relative;
top: 50px;
left: 120px;
}
In the example above, the element of green-box class will be moved
down 50 pixels, and to the right 120 pixels, from its default static
position. The image below displays the new position of the box.
Position: Absolute
.title {
position: fixed;
top: 0px;
left: 0px;
}
In the example above, the .title element will remain fixed to its
position no matter where the user scrolls on the page, like in the
image below:
Position: Sticky
Since static and relative positioned elements stay in the normal flow
of the document, when a user scrolls the page (or parent element)
these elements will scroll too. And since fixed and absolute positioned
elements are removed from the document flow, when a user scrolls,
these elements will stay at their specified offset position.
.box-bottom {
background-color: darkgreen;
position: sticky;
top: 240px;
}
Z-Index
.blue-box {
background-color: blue;
}
.green-box {
background-color: green;
position: relative;
top: -170px;
left: 170px;
}
In the example above, the .green-box element overlaps on top of
the .blue-box element.
The z-index property controls how far back or how far forward
an element should appear on the web page when elements
overlap.
.blue-box {
background-color: blue;
position: relative;
z-index: 1;
}
.green-box {
background-color: green;
position: relative;
top: -170px;
left: 170px;
}
Inline Display
In this lesson, we’ll cover three values for
the display property: inline, block, and inline-block.
The CSS display property provides the ability to make any element an
inline element. This includes elements that are not inline by
default such as paragraphs, divs, and headings.
h1 {
display: inline;
}
The CSS in the example above will change the display of
all <h1> elements to inline. The browser will render <h1> elements on
the same line as other inline elements immediately before or after
them (if there are any).
Display: Block
These elements fill the entire width of the page by default, but
their width property can also be set. Unless otherwise specified,
they are the height necessary to accommodate their content.
strong {
display: block;
}
Display: Inline-Block
For example, the <div>s below will be displayed on the same line and
with the specified dimensions:
<div class="rectangle">
<p>I’m a rectangle!</p>
</div>
<div class="rectangle">
<p>So am I!</p>
</div>
<div class="rectangle">
<p>Me three!</p>
</div>
.rectangle {
display: inline-block;
width: 200px;
height: 300px;
}
There are three rectangular divs that each contain a paragraph of
text. The .rectangle <div>s will all appear inline (provided there is
enough space from left to right) with a width of 200 pixels and height
of 300 pixels, even though the text inside of them may not require
200 pixels by 300 pixels of space.
Float
The float property is often set using one of the values below:
.green-section {
width: 50%;
height: 150px;
}
.orange-section {
background-color: orange;
width: 50%;
float: right;
}
Clear
left—the left side of the element will not touch any other
element within the same containing element.
right—the right side of the element will not touch any other
element within the same containing element.
both—neither side of the element will touch any other element
within the same containing element.
none—the element can touch either side.
div {
width: 200px;
float: left;
}
div.special {
clear: left;
}
In the example above, all <div>s on the page are floated to the left
side. The element with class special did not move all the way to
the left because a taller <div> blocked its positioning. By
setting its clear property to left, the special <div> will be moved
all the way to the left side of the page.
COLOR
Hexadecimal
One syntax that we can use to specify colors is called hexadecimal. A
hex color begins with a hash character ( #) which is followed by three
or six characters. The characters represent values for red, blue and
green.
darkseagreen: #8FBC8F
sienna: #A0522D
saddlebrown: #8B4513
brown: #A52A2A
black: #000000 or #000
white: #FFFFFF or #FFF
aqua: #00FFFF or #0FF
In the example above, you may notice that there are both letters and
numbers in the values. This is because the hexadecimal number
system has 16 digits (0-15) instead of 10 (0-9) like in the standard
decimal system. To represent 10-15, we use A-F.
Notice that black, white, and aqua are all represented with both three
characters and six characters. This can be done with hex colors
whose number pairs are the same characters.
RGB Colors
h1 {
color: rgb(23, 45, 23);
}
Each of the three values represents a color component, and each can
have a decimal number value from 0 to 255. The first number
represents the amount of red, the second is green, and the third is
blue.
The syntax for HSL is similar to the decimal form of RGB, though it
differs in important ways. The first number represents the
degree of the hue, and can be between 0 and 360. The second
and third numbers are percentages representing saturation
and lightness respectively. Here is an example:
Lightness refers to how light or dark the color is. Halfway, or 50%, is
normal lightness. Sliding the dimmer up towards 100% makes the
color lighter, closer to white. Sliding the dimmer down towards 0%
makes the color darker, closer to black.
The first three values work the same as hsl. The fourth value
(which we have not seen before) is the alpha. This last value
is sometimes called opacity.
Alpha is a decimal number from zero to one. If alpha is zero,
the color will be completely transparent. If alpha is one, the
color will be opaque. The value for half-transparent would
be 0.5.
The RGB color scheme has a similar syntax for opacity, rgba. Again,
the first three values work the same as rgb and the last value is the
alpha. Here’s an example:
color: transparent;
Linear Gradient
Now you'll apply a red-to-green gradient along a 90 degree line to the first
marker.
First, in the .red CSS rule, set the background property to linear-
gradient(), and pass it the value 90deg as the gradientDirection.
You'll use the rgb function for the colors of this gradient.
In the linear-gradient function, use the rgb function to set the first color
argument to pure red.
You won't see gradient yet because the linear-gradient function needs at
least two color arguments to work.
In the same linear-gradient function, use the rgb function to set the
second color argument to pure green.
.red {
background: linear-gradient(90deg, rgb(255, 0, 0), rgb
(0, 255,0));
}
Color Stops
Color-stops allow you to fine-tune where colors are placed along the gradient
line. They are a length unit like px or percentages that follow a color in
the linear-gradient function.
For example, in this red-black gradient, the transition from red to black takes
place at the 90% point along the gradient line, so red takes up most of the
available space:
.red {
background: linear-gradient(90deg, rgb(255, 0, 0)
75%, rgb(0, 255, 0), rgb(0, 0, 255));
Box Shadow
The box-shadow property lets you apply one or more shadows around an
element. Here is basic syntax:
offset-x (how far to push the shadow horizontally from the element),
offset-y (how far to push the shadow vertically from the element),
As you can see, you added a simple red shadow around your marker
that's 5 pixels to the right, and 5 pixels down.
But what if you wanted to position your shadow on the opposite side?
You can do that by using negative values for offsetX and offsetY.
Notice that the edges of the shadow are sharp. This is because there is an
optional blurRadius value for the box-shadow property:
But what if you wanted to expand the shadow out further? You can do that with
the optional spreadRadius value:
TYPOGRAPHY
Font Family
Multi-Word Values
When specifying a typeface with multiple words, like Times New
Roman, it is recommended to use quotation marks (' ') to group the
words together, like so:
h1 {
font-family: 'Times New Roman';
}
There is a selection of fonts that will appear the same across all
browsers and operating systems. These fonts are referred to as web
safe fonts. You can check out a complete list of web safe
fonts here.
h1 {
font-family: Caslon, Georgia, 'Times New Roman';
}
The fonts Caslon, Georgia, and Times New Roman are Serif fonts. Serif
fonts have extra details on the ends of each letter, as opposed
to Sans-Serif fonts, which do not have the extra details.
serif and sans-serif are also keyword values that can be added as
a final fallback font if nothing else in the font stack is available.
h1 {
font-family: Caslon, Georgia, 'Times New Roman', serif;
}
In this final example, the font stack has 4 fonts. If the first 3 fonts
aren’t available, the browser will use whatever serif font is available
on the system.
Font Weight
In CSS, the font-weight property controls how bold or thin text
appears
The font-weight property can take any one of these keyword values:
bold--normal: lighter
bolder: One font weight bolder than the element’s parent value
Numerical Values
Numerical values can range from 1 (lightest) to 1000
(boldest), but it is common practice to use increments of 100.
A font weight of 400 is equal to the keyword value normal, and a
font weight of 700 is equal to bold.
.left-section {
font-weight: 700;
}
.right-section {
font-weight: bold;
}
Font Style
h3 {
font-style: italic;
}
Text Transformation
Text can also be styled to appear in either all uppercase or
lowercase or capitalize with the text-transform property.
h1 {
text-transform: uppercase;
}
Text Decoration
To underline text, you can use the u tag. This is often used to signify that a
section of text is important, or something to remember. With the u tag, the
browser applies the CSS of
h1 {
text-decoration: underlined;
}
Text Layout
Letter Spacing
p {
letter-spacing: 2px;
}
Word Spacing
You can set the space between words with the word-spacing property.
The word-spacing property also takes length values in units, such
as 3px or 0.2em.
h1 {
word-spacing: 0.3em;
}
In the example above, the word spacing is set to 0.3em. For word
spacing, using em values are recommended because the
spacing can be set based on the size of the font.
Line Height
We can use the line-height property to set how tall we want each
line containing our text to be. Line height values can be a
unitless number, such as 1.2, or a length value, such
as 12px, 5% or 2em.
p {
line-height: 1.4;
}
<head>
<!-- Add the link element for Google Fonts along with
other metadata -->
<link href="https://fonts.googleapis.com/css2?
family=Roboto:wght@100&display=swap" rel="stylesheet">
</head>
p {
font-family: 'Roboto', sans-serif;
}
You can then create font-family declarations in your CSS, just like
how you learned to do with other fonts!
The different formats are a progression of standards for how fonts will
work with different browsers, with WOFF2 being the most progressive.
It’s a good idea to include TTF, WOFF, and WOFF2 formats with
your @font-face rule to ensure compatibility on all browsers.
Within the “Selected Families” section, you can use the “Download”
button to download the font files to your computer. The files will be
downloaded as a single format, in this case, TTF. You can use a tool
such as Google Web Fonts Helper to generate additional file types for
WOFF and WOFF2.
When you have the files you need, move them to a folder inside your
website’s working directory, and you’re ready to use them in a @font-
face ruleset!
@font-face {
font-family: 'MyParagraphFont';
src: url('fonts/Roboto.woff2') format('woff2'),
url('fonts/Roboto.woff') format('woff'),
url('fonts/Roboto.ttf') format('truetype');
}
Let’s take a look at the example above, line by line:
Once the @font-face at-rule is defined, you can use the font in your
stylesheet!
p {
font-family: 'MyParagraphFont', sans-serif;
}
Like using any other fonts, you can use the font-family property to set
the font on any HTML element. The downloaded font can be
referenced with the name you provided as the font-family property’s
value in the @font-face ruleset—in this case, 'MyParagraphFont'.
--------------------------------//---------------------------------
The example above can be written using two separate rules as well:
And Operator
The and operator can be used to require multiple media features.
Therefore, we can use the and operator to require both a max-
width of 480px and to have a min-resolution of 300dpi.
img {
max-width: 100%;
height: auto;
}
The max-width of 100% will make sure the image is never wider than the
container it is in, and the height of auto will make the image keep its
original aspect ratio.
<style>
img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
Here is an example that sets a body tag to 30% of the viewport's width.
--------------------------------//---------------------------------
FLEXBOX
There are two important components to a flexbox layout: flex
containers and flex items. A flex container is an element on a
page that contains flex items. All direct child elements of a
flex container are flex items.
display: flex
div.container {
display: flex;
}
In the example above, all divs with the class container are flex
containers. If they have children, the children are flex items. A div
with the declaration display: flex; will remain block level —
no other elements will appear on the same line as it.
inline-flex
<div class='container'>
<p>I’m inside of a flex container!</p>
<p>A flex container’s children are flex items!</p>
</div>
<div class='container'>
<p>I’m also a flex item!</p>
<p>Me too!</p>
</div>
.container {
width: 200px;
height: 200px;
display: inline-flex;
}
Notice that in the example above, the size of the flex container is set.
Currently, the size of the parent container will override the size of its
child elements. If the parent element is too small, the flex items will
shrink to accommodate the parent container’s size.
<div class='container'>
<div class='child'>
<h1>1</h1>
</div>
<div class='child'>
<h1>2</h1>
</div>
</div>
.container {
width: 200px;
}
.child {
display: inline-flex;
width: 150px;
height: auto;
}
In the example above, the .child divs will take up more width (300
pixels) than the container div allows (200 pixels). The .child divs will
shrink to accommodate the container’s size.
justify-content
.container {
display: flex;
justify-content: flex-end;
}
In the example above, we set the value of justify-content to flex-end.
This will cause all of the flex items to shift to the right side of the flex
container.
.container {
align-items: baseline;
}
In the example above, the align-items property is set to baseline. This
means that the baseline of the content of each item will be aligned.
flex-grow
We learned that all flex items shrink proportionally when the flex
container is too small. However, if the parent container is larger than
necessary then the flex items will not stretch by default.
<div class='container'>
<div class='side'>
<h1>I’m on the side of the flex container!</h1>
</div>
<div class='center'>
<h1>I'm in the center of the flex container!</h1>
</div>
<div class='side'>
<h1>I'm on the other side of the flex container!</h1>
</div>
</div>
.container {
display: flex;
}
.side {
width: 100px;
flex-grow: 1;
}
.center {
width: 100px;
flex-grow: 2;
}
In the example above, the .container div has a display value
of flex, so its three child divs will be positioned next to each
other. If there is additional space in the .container div (in this case, if
it is wider than 300 pixels), the flex items will grow to fill it.
The .center div will stretch twice as much as the .side divs. For
example, if there were 60 additional pixels of space,
the center div would absorb 30 pixels and the side divs would
absorb 15 pixels each.
flex-shrink
You may have noticed in earlier exercises that flex items shrank when
the flex container was too small, even though we had not declared
the property. This is because the default value of flex-shrink is 1.
However, flex items do not grow unless the flex-grow property
is declared because the default value of flex-grow is 0.
<div class='container'>
<div class='side'>
<h1>I'm on the side of the flex container!</h1>
</div>
<div class='center'>
<h1>I'm in the center of the flex container!</h1>
</div>
<div class='side'>
<h1>I'm on the other side of the flex container!</h1>
</div>
</div>
.container {
display: flex;
}
.side {
width: 100px;
flex-shrink: 1;
}
.center {
width: 100px;
flex-shrink: 2;
}
In the example above, the .center div will shrink twice as much
as the .side divs if the .container div is too small to fit the
elements within it. If the content is 60 pixels too large for the
flex container that surrounds it, the .center div will shrink by
30 pixels and the outer divs will shrink by 15 pixels each.
Margins are unaffected by flex-grow and flex-shrink.
flex-basis
<div class='container'>
<div class='side'>
<h1>Left side!</h1>
</div>
<div class='center'>
<h1>Center!</h1>
</div>
<div class='side'>
<h1>Right side!</h1>
</div>
</div>
.container {
display: flex;
}
.side {
flex-grow: 1;
flex-basis: 100px;
}
.center {
flex-grow: 2;
flex-basis: 150px;
}
In the example above, the .side divs will be 100 pixels wide and
the .center div will be 150 pixels wide if the .container div has just the
right amount of space (350 pixels, plus a little extra for margins and
borders). If the .container div is larger, the .center div will absorb twice
as much space as the .side divs.
The same would hold true if we assigned flex-shrink values to the divs
above as well.
Flex
Note: The flex property is different from the flex value used for
the display property.
.big {
flex-grow: 2;
flex-shrink: 1;
flex-basis: 150px;
}
.small {
flex-grow: 1;
flex-shrink: 2;
flex-basis: 100px;
}
In the example above, all elements with class big will grow twice as
much as elements with class small. Keep in mind, this doesn’t
mean big items will be twice as big as small items, they’ll just take up
more of the extra space.
.big {
flex: 2 1 150px;
}
.small {
flex: 1 2 100px;
}
In the example above, we use the flex property to declare the values
for flex-grow, flex-shrink, and flex-basis (in that order) all in one line.
.big {
flex: 2 1;
}
In the example above, we use the flex property to declare flex-
grow and flex-shrink, but not flex-basis.
.small {
flex: 1 20px;
}
In the example above, we use the flex property to declare flex-
grow and flex-basis. Note that there is no way to set only flex-
shrink and flex-basis using 2 values.
flex-wrap
<div class='container'>
<div class='item'>
<h1>We're going to wrap!</h1>
</div>
<div class='item'>
<h1>We're going to wrap!</h1>
</div>
<div class='item'>
<h1>We're going to wrap!</h1>
</div>
</div>
.container {
display: inline-flex;
flex-wrap: wrap;
width: 250px;
}
.item {
width: 100px;
height: 100px;
}
In the example above, three flex items are contained by a parent flex
container. The flex container is only 250 pixels wide so the
three 100 pixel wide flex items cannot fit inline. The flex-wrap:
wrap; setting causes the third, overflowing item to appear on a
new line, below the other two items.
Now that elements can wrap to the next line, we might have multiple
rows of flex items within the same container. The align-items is for
aligning elements within a single row. If a flex container has
multiple rows of content, we can use align-content to space the
rows from top to bottom.
<div class='container'>
<div class='child'>
<h1>1</h1>
</div>
<div class='child'>
<h1>2</h1>
</div>
<div class='child'>
<h1>3</h1>
</div>
<div class='child'>
<h1>4</h1>
</div>
</div>
.container {
display: flex;
width: 400px;
height: 400px;
flex-wrap: wrap;
align-content: space-around;
}
.child {
width: 150px;
height: 150px;
}
In the example above, there are four flex items inside of a flex
container. The flex items are set to be 150 pixels wide each,
but the parent container is only 400 pixels wide.
This means that no more than two elements can be displayed inline.
The other two elements will wrap to the next line and there will be
two rows of divs inside of the flex container. The align-content property
is set to the value of space-around, which means the two rows of divs
will be evenly spaced from top to bottom of the parent container with
equal space before the first row and after the second, with double
space between the rows.
align-self
This property allows you to adjust each item's alignment individually, instead of
setting them all at once. This is useful since other common adjustment
techniques using the CSS properties float, clear, and vertical-align do
not work on flex items.
#box-2 {
background-color: orangered;
align-self: flex-end;
height: 200px;
width: 200px;
flex-direction
Up to this point, we’ve only covered flex items that stretch and shrink
horizontally and wrap vertically. As previously stated, flex containers
have two axes: a main axis and a cross axis. By default, the main
axis is horizontal and the cross axis is vertical.
The main axis is used to position flex items with the following
properties:
1. justify-content
2. flex-wrap
3. flex-grow
4. flex-shrink
The cross axis is used to position flex items with the following
properties:
1. align-items
2. align-content
<div class='container'>
<div class='item'>
<h1>1</h1>
</div>
<div class='item'>
<h1>2</h1>
</div>
<div class='item'>
<h1>3</h1>
</div>
<div class='item'>
<h1>4</h1>
</div>
<div class="item">
<h1>5</h1>
</div>
</div>
.container {
display: flex;
flex-direction: column;
width: 1000px;
}
.item {
height: 100px;
width: 100px;
}
In the example above, the five divs will be positioned in a vertical
column. All of these divs could fit in one horizontal row. However,
the column value tells the browser to stack the divs one on top of the
other. As explained above, properties like justify-content will not
behave the way they did in previous examples.
The flex-direction property can accept four values:
flex-flow
.container {
display: flex;
flex-wrap: wrap;
flex-direction: column;
}
.container {
display: flex;
flex-flow: column wrap;
}
In the example above, the first value in the flex-flow declaration
is a flex-direction value and the second is a flex-wrap value. All
values for flex-direction and flex-wrap are accepted.
Nested Flexboxes
<div class='container'>
<div class='left'>
<img class='small' src='#'/>
<img class='small' src='#'/>
<img class='small' src='#' />
</div>
<div class='right'>
<img class='large' src='#' />
</div>
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
}
.left {
display: inline-flex;
flex: 2 1 200px;
flex-direction: column;
}
.right {
display: inline-flex;
flex: 1 2 400px;
align-items: center;
}
.small {
height: 200px;
width: auto;
}
.large {
height: 600px;
width: auto;
}
In the example above, a div with three smaller images will display
from top to bottom on the left of the page ( .left). There is also a div
with one large image that will display on the right side of the page
(.right). The left div has a smaller flex-basis but stretches to fill more
extra space; the right div has a larger flex-basis but stretches to fill
less extra space. Both divs are flex items and flex containers.
--------------------------------//---------------------------------
CSS GRID
Whereas Flexbox is mostly useful for positioning items in a one-
dimensional layout, CSS grid is most useful for two-dimensional
layouts, providing many tools for aligning and moving elements
across both rows and columns.
Creating a Grid
To set up a grid, you need to have both a grid container and grid
items.
To turn an HTML element into a grid container, you must set the
element’s display property to one of two values:
Creating Columns
.grid {
display: grid;
width: 500px;
grid-template-columns: 100px 200px;
}
This property creates two changes. First, it defines the
number of columns in the grid; in this case, there are two.
Second, it sets the width of each column. The first column will be
100 pixels wide and the second column will be 200 pixels wide.
.grid {
display: grid;
width: 1000px;
grid-template-columns: 20% 50%;
}
In this example, the grid is 1000 pixels wide. Therefore, the first
column will be 200 pixels wide because it is set to be 20% of the
grid’s width. The second column will be 500 pixels wide.
We can also mix and match these two units. In the example below,
there are three columns of width 20 pixels, 40 pixels, and 60 pixels:
.grid {
display: grid;
width: 100px;
grid-template-columns: 20px 40% 60px;
}
In this example, the total width of our columns (120 pixels) exceeds
the width of the grid (100 pixels). This might make our grid cover
other elements on the page!
Creating Rows
.grid {
display: grid;
width: 1000px;
height: 500px;
grid-template-columns: 100px 200px;
grid-template-rows: 10% 20% 600px;
}
This grid has two columns and three rows. grid-template-rows defines
the number of rows and sets each row’s height. In this example,
the first row is 50 pixels tall (10% of 500), the second row is 100
pixels tall (20% of 500), and the third row is 600 pixels tall.
Grid Template
.grid {
display: grid;
width: 1000px;
height: 500px;
grid-template: 200px 300px / 20% 10% 70%;
}
Fraction
By using the fr unit, we can define the size of columns and rows as a
fraction of the grid’s length and width. This unit was specifically
created for use in CSS Grid.
.grid {
display: grid;
width: 1000px;
height: 400px;
grid-template: 2fr 1fr 1fr / 1fr 3fr 1fr;
}
In this example, the grid will have three rows and three columns. The
rows are splitting up the available 400 pixels of height into four parts.
The first row gets two of those parts, the second row gets one, and
the third row gets one. Therefore the first row is 200 pixels tall, and
the second and third rows are 100 pixels tall.
.grid {
display: grid;
width: 100px;
grid-template-columns: 1fr 60px 1fr;
}
In this example, 60 pixels are taken up by the second column.
Therefore the first and third columns have 40 available to
split between them. Since each gets one fraction of the total,
they both end up being 20 pixels wide.
Repeat
The properties that define the number of rows and columns in a grid
can take a function as a value. repeat() is one of these functions.
The repeat() function was created specifically for CSS Grid.
.grid {
display: grid;
width: 300px;
grid-template-columns: repeat(3, 100px);
}
Repeat is particularly useful with fr. For example, repeat(5, 1fr) would
split your table into five equal rows or columns.
Minmax
In these situations, you might want to prevent a row or column from
getting too big or too small. For example, if you have a 100-pixel wide
image in your grid, you probably don’t want its column to get thinner
than 100 pixels! The minmax() function can help us solve this problem.
.grid {
display: grid;
grid-template-columns: 100px minmax(100px, 500px) 100px;
}
In this example, the first and third columns will always be 100
pixels wide, no matter the size of the grid. The second
column, however, will vary in size as the overall grid resizes.
The second column will always be between 100 and 500 pixels
wide.
Grid Gap
In all of our grids so far, there hasn’t been any space between the
items in our grid. The CSS properties row-gap and column-gap will put
blank space between every row and column in the grid.
.grid {
display: grid;
width: 320px;
grid-template-columns: repeat(3, 1fr);
column-gap: 10px;
}
It is important to note that grid gap properties does not add space at
the beginning or end of the grid. In the example code, our grid will
have three columns with two ten-pixel gaps between them.
.grid {
display: grid;
width: 320px;
grid-template-columns: repeat(3, 1fr);
gap: 20px 10px;
}
The example above will set the distance between rows to 20 pixels
and the distance between columns to 10 pixels. Unlike other CSS
grid properties, this shorthand does not take a / between
values! If only one value is given, it will set the column gap
and the row gap to that value.
.item {
grid-row-start: 1;
grid-row-end: 3;
}
In this example, the HTML element of class item will take up two rows
in the grid, rows 1 and 2. The values that grid-row-start and grid-row-
end accept are grid lines.
Row grid lines and column grid lines start at 1 and end at a value that
is 1 greater than the number of rows or columns the grid has. For
example, if a grid has 5 rows, the grid row lines range from 1
to 6. If a grid has 8 rows, the grid row lines range from 1 to 9.
Grid Row
.item {
grid-row-start: 4;
grid-row-end: 6;
}
.item {
grid-row: 4 / 6;
}
This code should look similar to the way grid-template is shorthand
for grid-template-rowsand grid-template-columns. In this case, the starting
row goes before the “/“ and the ending row goes after it.
Grid Column
When using these properties, we can use the keyword span to start
or end a column or row, relative to its other end. Look at
how span is used in the code below:
.item {
grid-column: 4 / span 2;
}
This is telling the item element to begin in column four and take
up two columns of space. So item would occupy columns four
and five. It produces the same result as the following code blocks:
.item {
grid-column: 4 / 6;
}
.item {
grid-column-start: 4;
grid-column-end: span 2;
}
.item {
grid-column-start: span 2;
grid-column-end: 6;
}
span is a useful keyword, because it avoids off-by-one errors
(miscalculating the ending grid line) you might make when
determining the ending grid line of an element. If you know where
you want your grid item to start and how long it should be, use span!
Grid Area
.item {
grid-area: 2 / 3 / 4 / span 5;
}
grid-area takes four values separated by slashes. The order is
important! This is how grid-area will interpret those values.
1. grid-row-start
2. grid-column-start
3. grid-row-end
4. grid-column-end
In the above example, the item will occupy rows two and three and
columns three through eight.
--------------------------------//---------------------------------
<div class="container">
<header>Welcome!</header>
<nav>Links!</nav>
<section class="info">Info!</section>
<section class="services">Services!</section>
<footer>Contact us!</footer>
</div>
.container {
display: grid;
max-width: 900px;
position: relative;
margin: auto;
grid-template-areas: "head head"
"nav nav"
"info services"
"footer footer";
grid-template-rows: 300px 120px 800px 120px;
grid-template-columns: 1fr 3fr;
}
header {
grid-area: head;
}
nav {
grid-area: nav;
}
.info {
grid-area: info;
}
.services {
grid-area: services;
}
footer {
grid-area: footer;
}
1. In the example above, the HTML creates a web page with five
distinct parts.
2. In the .container ruleset, the grid-template-areas declaration
creates a 2-column, 4-row layout.
3. The grid-template-rows declaration specifies the height of each of
the four rows from top to bottom: 300 pixels, 120 pixels, 800
pixels, and 120 pixels.
4. The grid-template-columns declaration uses the fr value to cause
the left column to use one fourth of the available space on the
page and the right column to use three-fourths of the available
space on the page.
5. In each ruleset below .container, we use the grid-area property
to tell that section to cover the portion of the page specified.
The header element spans the first row and both columns.
The nav element spans the second row and both columns. The
element with class .info spans the third row and left column.
The element with class .services spans the third row and right
column. The footer element spans the bottom row and both
columns.
Overlapping Elements
<div class="container">
<div class="info">Info!</div>
<img src="#" />
<div class="services">Services!</div>
</div>
.container {
display: grid;
grid-template: repeat(8, 200px) / repeat(6, 100px);
}
.info {
grid-area: 1 / 1 / 9 / 4;
}
.services {
grid-area: 1 / 4 / 9 / 7;
}
img {
grid-area: 2 / 3 / 5 / 5;
z-index: 5;
}
In the example above, there is a grid container with eight rows and
six columns. There are three grid items within the container —
a <div> with the class info, a <div> with the class services, and an
image.
The info section covers all eight rows and the first three columns.
The services section covers all eight rows and the last three columns.
The image spans the 2nd, 3rd, and 4th rows and the 3rd and 4th
columns.
Justify Items
There are two axes in a grid layout — the column (or block) axis and
the row (or inline) axis.The column axis stretches from top to bottom
across the web page. The row axis stretches from left to right across
the web page.
<main>
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
</main>
main {
display: grid;
grid-template-columns: repeat(3, 400px);
justify-items: center;
}
Justify Content
We learned how to position elements within their columns. In this
exercise, we will learn how to position a grid within its parent
element.
We can use justify-content to position the entire grid along the row
axis.
start — aligns the grid to the left side of the grid container— end —
center —
stretch — stretches the grid items to increase the size of the grid to
expand horizontally across the container
space-around —space-between —
space-evenly — places an even amount of space between grid items
and at either end
<main>
<div class="left">Left</div>
<div class="right">Right</div>
</main>
main {
display: grid;
width: 1000px;
grid-template-columns: 300px 300px;
grid-template-areas: "left right";
justify-content: center;
}
1. In the example above, the grid container is 1000 pixels wide, but we
only specified two columns that are 300 pixels each. This will leave
400 pixels of unused space in the grid container.
2. justify-content: center; positions the columns in the center of the
grid, leaving 200 pixels on the right and 200 pixels on the left of the
grid.
Align Items
Now we’ll learn how to position grid items from top to bottom!
is a property that positions grid items along the block, or
align-items
column axis. This means that it positions items from top to bottom.
start — aligns grid items to the top side of the grid area— end —
center —
stretch — stretches all items to fill the grid area
<main>
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
</main>
main {
display: grid;
grid-template-rows: repeat(3, 400px);
align-items: center;
}
In the example above, we use align-items to adjust the positioning of
some elements on this web page.
1. There is a grid container with three rows that are 400 pixels tall.
2. By setting the align-items property to center, the .card <div>s will be
centered vertically inside of their rows. They will only be as tall as
necessary to contain their content (the words Card 1, etc).
3. If we specify a height for the .card elements, they will not stretch the
height of their row even if align-items: stretch; is set.
Align Content
In the previous exercise, we positioned grid items within their
rows. align-content positions the rows along the column axis, or from
top to bottom, and is declared on grid containers.
start — aligns the grid to the top of the grid container— end —
center —
stretch — stretches the grid items to increase the size of the grid to
expand vertically across the container
space-around —space-between —space-evenly — places an even amount
of space between grid items and at either end
<main>
<div class="top">Top</div>
<div class="bottom">Bottom</div>
</main>
main {
display: grid;
height: 600px;
grid-template-rows: 200px 200px;
grid-template-areas: "top"
"bottom";
align-content: center;
}
1. In the example above, the grid container is 600 pixels tall, but we
only specified two rows that are 200 pixels each. This will leave 200
pixels of unused space in the grid container.
2. align-content: center; positions the rows in the center of the grid,
leaving 100 pixels at the top and 100 pixels at the bottom of the grid.
The justify-items and align-items properties specify how all grid items
contained within a single container will position themselves along the
row and column axes, respectively.
start — positions grid items on the left side/top of the grid area
end — positions grid items on the right side/bottom of the grid
area
center — positions grid items on the center of the grid area
stretch — positions grid items to fill the grid area (default)
Something called the implicit grid takes over. The implicit grid is an
algorithm built into the specification for CSS Grid that determines
default behavior for the placement of elements when there are more
than fit into the grid specified by the CSS.
pixels (px)
percentages (%)
fractions (fr)
the repeat() function
<body>
<div>Part 1</div>
<div>Part 2</div>
<div>Part 3</div>
<div>Part 4</div>
<div>Part 5</div>
</body>
body {
display: grid;
grid: repeat(2, 100px) / repeat(2, 150px);
grid-auto-rows: 50px;
}
In the example above, there are 5 <div>s. However, in the body ruleset,
we only specify a 2-row, 2-column grid — four grid cells.
You can pair row or column with dense, like this: grid-auto-flow: row
dense;.
--------------------------------//---------------------------------
CSS TRANSITIONS
Duration
To create a simple transition in CSS, we must specify two of the four
aspects:
a {
transition-property: color;
transition-duration: 1s;
}
Timing Function
transition-property: color;
transition-duration: 1s;
transition-timing-function: ease-out;
In the example above, the text color will be animated over one
second. The timing function is ease-out which means it will begin
abruptly and slow down as it ends.
Delay
transition-property: width;
transition-duration: 750ms;
transition-delay: 250ms;
In the example above, a change in the width of the element will start
after a quarter of a second, and it will animate over three quarters of
a second.
Shorthand
transition-property: color;
transition-duration: 1.5s;
transition-timing-function: linear;
transition-delay: 0.5s;
Combinations
The shorthand transition rule has one advantage over the set of
separate transition-<property> rules: you can describe unique
transitions for multiple properties, and combine them.
The above code transitions two properties at once. The text color
transitions over one second with linear timing and no delay. At the
same time, the font size transitions over 750 milliseconds with
an ease-in timing and a 100 millisecond delay. This “chaining” is a
powerful tool for expressing complicated animations.
All
It is common to use the same duration, timing function, and delay for
multiple properties. When this is the case you can set
the transition-property value to all. This will apply the same
values to all properties.
all means every value that changes will be transitioned in the same
way. You can use all with the separate transition properties, or the
shorthand syntax.
--------------------------------//---------------------------------
SIZING ELEMENTS
Em
The em represents the font-size of the current element or the default
base font-size set by the browser if none is given. For example, if the
base font of a browser is 16 pixels (which is normally the
default size of text in a browser), then 1 em is equal to 16
pixels. 2 ems would equal 32 pixels, and so on.
.heading {
font-size: 2em;
}
In the example above, no base font has been specified, therefore the
font size of the heading element will be set relative to the default font
size of the browser. Assuming the default font size is 16 pixels, then
the font size of the heading element will be 32 pixels.
.splash-section {
font-size: 18px;
}
.splash-section h1 {
font-size: 1.5em;
}
Instead, a base font size (18px) is defined for all text within the splash-
section element. The second CSS rule will set the font size of
all h1 elements inside of splash-section relative to the base font
of splash-section (18 pixels). The resulting font size of h1 elements will
be 27 pixels.
Rem
Rem stands for root em. It acts similar to em, but instead of checking
parent elements to size font, it checks the root element. The root
element is the <html> tag.
html {
font-size: 20px;
}
h1 {
font-size: 2rem;
}
In the example above, the font size of the root element, <html>, is set
to 20 pixels. All subsequent rem measurements will now be compared
to that value and the size of h1 elements in the example will be 40
pixels.
.container {
width: 50%;
height: 200px;
overflow: hidden;
}
.container img {
max-width: 100%;
height: auto;
display: block;
}
The second CSS rule ensures that images scale with the width of the
container. The height property is set to auto, meaning an image’s
height will automatically scale proportionally with the width. Finally,
the last line will display images as block level elements (rather than
inline-block, their default state).
The final declaration, however, is the focus of the example above. It’s
what scales the background image. The image will cover the entire
background of the element, all while keeping the image in proportion.
If the dimensions of the image exceed the dimensions of the
container then only a portion of the image will display.
FREECODECAMP
NOTA: Change the width property's value to be 80%, to make it is 80% the
width of its parent element (body).
NOTA: You change properties of a link when the link has actually been visited
by using a pseudo-selector that looks like a:visited { propertyName:
propertyValue; }.
Change the color of the footer Visit our website link to be grey when
a user has visited the link.
NOTA: You change properties of a link when the mouse hovers over them by
using a pseudo-selector that looks like a:hover { propertyName:
propertyValue; }.
NOTA: The menu text CAMPER CAFE has a different space from the top than
the address at the bottom of the menu. This is due to the browser having
some default top margin for the h1 element.
Change the top margin of the h1 element to 0 to remove all the top
margin.
NOTA: It would be nice if the vertical space between the h2 elements and their
associated icons was smaller. The h2 elements have default top and bottom
margin space, so you could change the bottom margin of the h2 elements
to say 0 or another number.
NOTA: For this challenge, you will use the [attr=value] attribute selector to
style the checkboxes in CatPhotoApp. This selector matches and styles
elements with a specific attribute value. For example, the below code changes
the margins of all elements with the attribute type and a corresponding value
of radio:
[type='radio'] {
p {
transform: scale(2);
}
The next function of the transform property is skewX(), which skews the
selected element along its X (horizontal) axis by a given degree.
The following code skews the paragraph element by -32 degrees along the X-
axis.
p {
transform: skewX(-32deg);
}
.heart::before {
content: "";
background-color: yellow;
border-radius: 25%;
position: absolute;
height: 50px;
width: 70px;
top: -50px;
left: 5px;
For the ::before and ::after pseudo-elements to function properly, they
must have a defined content property. This property is usually
used to add things like a photo or text to the selected element.
In the above example, the element with the class of heart has
a ::before pseudo-element that produces a yellow rectangle with height
and width of 50px and 70px, respectively. This rectangle has round
corners due to its 25% border-radius and is positioned absolutely
at 5px from the left and 50px above the top of the element.