Lab 08 Positioning
Goal
- Learn CSS property
position
using the values fixed, relative, and absolute. - Utilize CSS properties
top
,bottom
,left
, andright
to move position absolute and fixed elements around
Learn
position:static;
position:fixed;
position:relative;
position:absolute;
position
Position property sets how an element is positioned in a document. Using the top, right, bottom, and left properties with position will determine the final location of positioned elements.
Values for position
- static - By default all HTML elements default to position static. This means the elements position is determined by the order in which it is listed in the HTML document.
- fixed - When applied to an HTML element, the element is removed from the normal document flow, and no space is created for the element in the page layout. A position fixed element's location will be based on the whole
body
. Then top, left, right, and bottom properties are used to place the element in a specific position on the web page. - relative - Relative HTML elements remain in the flow of the document, but tells the browser that any absolute HTML elements in the container are positioned based on its relative container.
- absolute - Absolute element's location will be based by the nearest relative element. If there is no relative parent element, the absolute element will be based on the
body
similar to position fixed elements.
top:10rem;
left:0;
right:35%;
bottom:5px;
top
& bottom
Specifies the vertical position of a positioned element.
left
& right
Specifies the horizontal positioning of a positioned element.
All four CSS properties will have no effect on non-positioned elements.
Values for top, right, bottom, and left:
- Percentages, are relative to the parent element's padding. So if a paragraph element is inside a main element, and the main element's padding is 100 pixels and you set the paragraph element's width to 50%. It will be 50 pixels.
- Pixels.
- Ems, these are dynamic and like percentages are based on the relative font-size of the parent of the element. Browsers default to 16px equals 1em on the body tag
- Rems, are similar to ems and percentage in that their size is relative, but rems are only relative to the html root tag not the direct parent of a tag. Rems too default to 16px equal 1rem on the html tag.
Hint: When using the value 0 for any of the properties above a unit is not needed, the value is simply 0.
z-index
The z-index CSS property sets the z-order of a positioned element and its descendants or flex items. An elements default z-index is 0. To move it up or down use positive or negative integers.
Practice
Experiment Try scrolling in the preview window below. Notice how the fixed element remains in place. Now try adding bottom and left CSS properties to get the fixed element in the bottom left corner.
HTML
CSS
Preview
Experiment Try using position absolute, top, and right on the exit class to move the x to the top right corner of the white box. Remember when using position absolute you need to add position relative to the container you want its location to be based on.
HTML
CSS
Preview
Experiment Try changing the z-index on the move-me class to 3, 5, -3, -5 to see how it stacks above or below the other objects.
HTML
CSS
Preview
Open GitHub Desktop (you may need to download the program again if the computers get wiped.)
Couple of things to check in GitHub Desktop.
- Check to see if it says Pull Origin. If it does, click Pull Origin. Why? A pull occurs if you or a collaborator made a change to the repository and pushed the changes. ALWAYS MAKE SURE TO PULL BEFORE CODING!
- If the computers were wiped you made need to reclone your repository to the computer.
With your cs-318 repository selected, Click open in Visual Studio code.
Create a new folder called lab8
Create a new file called index.html in the lab8 folder
Setup your HTML files
Create your stylesheet
Link your stylesheet to the HTML
Change Document in the <title>
element to "Animals"
Create an images folder
Save the following images in your images folder
HTML
Add a header and main in the body
Add a nav with three a in the header
In each a add the following content and href values
- Sloth - href
#sloth
- Elephant - href
#elephant
- Owl - href
#owl
After the nav add a h1 with the content "Animals"
In the main add four sections
Section 1
Add a class="animals"
to the section
Add a h2 with the content "Animals"
Section 2
Add a class="sloth"
to section
Add an id="sloth"
to section
Add a h2 with the content "Sloth"
Add an article element
In the article add:
h2 "Choloepus"
h3 "Scientific Classification"
ul
- Kingdom: Animalia
- Phylum: Chordata
- Class: Mammalia
- Order: Pilosa
two paragraphs
- Sloths are a group of arboreal Neotropical xenarthran mammals, constituting the suborder Folivora. Noted for their slowness of movement, they spend most of their lives hanging upside down in the trees of the tropical rainforests of South America and Central America. They are considered to be most closely related to anteaters, together making up the xenarthran order Pilosa. There are six extant sloth species in two genera Bradypus (three-toed sloths) and Choloepus (two-toed sloths). Despite this traditional naming, all sloths actually have three toes on each rear limb, although two-toed sloths have only two digits on each forelimb. The two groups of sloths are from different, distantly related families, and are thought to have evolved their morphology via parallel evolution from terrestrial ancestors. Besides the extant species, many species of ground sloths ranging up to the size of elephants (like Megatherium) inhabited both North and South America during the Pleistocene Epoch. However, they became extinct during the Quaternary extinction event around 12,000 years ago, together with most large bodied animals in the New World. The extinction correlates in time with the arrival of humans, but climate change has also been suggested to have contributed. Members of an endemic radiation of Caribbean sloths formerly lived in the Greater Antilles. They included both ground and arboreal forms which became extinct after humans settled the archipelago in the mid-Holocene, around 6,000 years ago.
- Sloths are so named because of their very low metabolism and deliberate movements. Sloth, related to slow, literally means "laziness," and their common names in several other languages (e.g. French paresseux) also mean "lazy" or similar. Their slowness permits their low-energy diet of leaves and avoids detection by predatory hawks and cats that hunt by sight. Sloths are almost helpless on the ground, but are able to swim. The shaggy coat has grooved hair that is host to symbiotic green algae which camouflage the animal in the trees and provide it nutrients. The algae also nourish sloth moths, some species of which exist solely on sloths.
Section 3
Add a class="elephant"
to the section
Add an id="elephant"
to the section
Add a h2 with the content "Elephant"
Add an article element
In the article add:
h2 "Loxodonta"
h3 "Scientific Classification"
ul
- Kingdom: Animalia
- Phylum: Chordata
- Class: Mammalia
- Order: Proboscidea
- Family: Elephantidae
four paragraphs
- Elephants, the largest existing land animals, are mammals of the family Elephantidae. Three species are currently recognized: the African bush elephant, the African forest elephant, and the Asian elephant. Elephantidae is the only surviving family of the order Proboscidea; extinct members include the mastodons. The family Elephantidae also contains several now-extinct groups, including the mammoths and straight-tusked elephants. African elephants have larger ears and concave backs, whereas Asian elephants have smaller ears, and convex or level backs. Distinctive features of all elephants include a long trunk, tusks, large ear flaps, massive legs, and tough but sensitive skin. The trunk, also called a proboscis, is used for breathing, bringing food and water to the mouth, and grasping objects. Tusks, which are derived from the incisor teeth, serve both as weapons and as tools for moving objects and digging. The large ear flaps assist in maintaining a constant body temperature as well as in communication. The pillar-like legs carry their great weight.
- Elephants are scattered throughout sub-Saharan Africa, South Asia, and Southeast Asia and are found in different habitats, including savannahs, forests, deserts, and marshes. They are herbivorous, and they stay near water when it is accessible. They are considered to be keystone species, due to their impact on their environments. Other animals tend to keep their distance from elephants; the exception is their predators such as lions, tigers, hyenas, and wild dogs, which usually target only young elephants (calves). Elephants have a fission-fusion society, in which multiple family groups come together to socialize. Females (cows) tend to live in family groups, which can consist of one female with her calves or several related females with offspring. The groups, which do not include bulls, are led by the (usually) oldest cow, known as the matriarch.
- Males (bulls) leave their family groups when they reach puberty, and may live alone or with other males. Adult bulls mostly interact with family groups when looking for a mate. They enter a state of increased testosterone and aggression known as musth, which helps them gain dominance over other males as well as reproductive success. Calves are the centre of attention in their family groups and rely on their mothers for as long as three years. Elephants can live up to 70 years in the wild. They communicate by touch, sight, smell, and sound; elephants use infra-sound, and seismic communication over long distances. Elephant intelligence has been compared with that of primates and cetaceans. They appear to have self-awareness, as well as appearing to show empathy for dying and dead family members.
- African elephants are listed as vulnerable and Asian elephants as endangered by the International Union for Conservation of Nature (IUCN). One of the biggest threats to elephant populations is the ivory trade, as the animals are poached for their ivory tusks. Other threats to wild elephants include habitat destruction and conflicts with local people. Elephants are used as working animals in Asia. In the past, they were used in war; today, they are often controversially put on display in zoos, or exploited for entertainment in circuses. Elephants are highly recognizable and have been featured in art, folklore, religion, literature, and popular culture.
Section 4
Add a class="owl"
to the section
Add an id="owl"
to the section
Add a h2 with the content "Owl"
Add an article element
In the article add:
h2 "Tytonidae"
h3 "Scientific Classification"
ul
- Kingdom: Animalia
- Phylum: Chordata
- Class: Aves
- Order: Strigiformes
three paragraphs
- Owls are birds from the order Strigiformes, which includes about 200 species of mostly solitary and nocturnal birds of prey typified by an upright stance, a large, broad head, binocular vision, binaural hearing, sharp talons, and feathers adapted for silent flight. Exceptions include the diurnal northern hawk-owl and the gregarious burrowing owl.
- Owls hunt mostly small mammals, insects, and other birds, although a few species specialize in hunting fish. They are found in all regions of the Earth except polar ice caps and some remote islands.
- Owls are divided into two families: the true (or typical) owl family, Strigidae, and the barn-owl family, Tytonidae.
CSS
Make your browser window narrow about 500 or less pixels.
body
Background color #27213C
margin 0
font color #fff
font family 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif
header
background color rgba (39, 33, 60, .70)
display flex
flex-direction column-reverse
Use align-items to position the h1 and nav as seen below.
Possible values: flex-start, flex-end, center, stretch, baseline
nav>a
font color #e2512d
text decoration none
padding 1rem 2rem
font weight 900
display inline-block
nav>a:hover
font color #A33B20
text decoration underline
Back to the HTML
Add the following code right after the opening <body>
<iframe width="560" height="315" src="https://www.youtube.com/embed/UuWr5TCbumI?controls=0&autoplay=1&fs=0&loop=1&modestbranding=1&mute=1&playlist=UuWr5TCbumI" allowfullscreen class="animal-background"></iframe>
The iframe above has some customization added to the video to:
- autoplay
- remove the video player controls
- loop the video
- mute the video
- have only one video in the playlist
Back to CSS
header
position fixed.
This will fixed the header in one spot within the web page.
top 0.
This will make the headers fixed position at the top of the web page.
width 100%
This will make the header take up 100% of the width of the web page. When using position fixed if you want something to take up the entire width you need to use width:100%.
z-index.
Right now if you hover over the links in the nav you will not be able to click on them. The main is transparent and covering the header. Push the header in front of the main by changing the z-index of the header. By default all elements have a z-index of 0. If you want to move them forward use positive numbers starting at 1, and if you want to move it back use negative numbers starting at -1.
.animal-background
position fixed
top -12rem
width 200%
left -51%
height 50rem;
z-index -1
background image animal.jpg.
We are adding this so when the video is loading there is something else to fill the space.
background size cover
section>h2
text-align center
padding 13rem 0
text-shadow 2px 2px 2px #27213C
background-size cover
margin 0
section
background color #A33B20
.animals
background color transparent
.sloth>h2
background-image sloth.jpg
.elephant>h2
background-image elephant.jpg
.owl>h2
background-image owl.jpg
article
padding 1rem
In the HTML document for sections 2-4 add <span>^</span>
in the <h2>
after the content; Sloth, Elephant, Owl.
section span
position absolute
top 15rem
font-size 2rem
left:calc(50% - 11px);
section>h2
position relative.
Remember when using position absolute you need to add position relative to which ever parent element you want the absolute element's position to be based on.
Create a new file called scripts.js
Paste the follow javascript in to the new file and save
//Sloth Section
document.addEventListener("DOMContentLoaded", function(){
document.querySelector('.sloth>.accordion').addEventListener('click', function(){
document.querySelector('.sloth>article').classList.toggle('show');
document.querySelector('.sloth span').classList.toggle('rotate');
});
});
//Elephant Section
document.addEventListener("DOMContentLoaded", function(){
document.querySelector('.elephant>.accordion').addEventListener('click', function(){
document.querySelector('.elephant>article').classList.toggle('show');
document.querySelector('.elephant span').classList.toggle('rotate');
});
});
//Owl Section
document.addEventListener("DOMContentLoaded", function(){
document.querySelector('.owl>.accordion').addEventListener('click', function(){
document.querySelector('.owl>article').classList.toggle('show');
document.querySelector('.owl span').classList.toggle('rotate');
});
});
We will be using the script above to create an accordion, where the user will click on the caret below the h2 and the article will appear below it. Also we will be rotating the caret to indicate whether the article is open or not.
Javascript function breakdown (looking at just the sloth section function):
- Line 1: Add event listener function that will load after the entire HTML document has loaded. This is important because we will be calling the script file in the head which will load before any of the HTML in the body. So if we didn't call this function none of the following functions would work because they are based on selectors in the body.
- Line 2: Look for the selector
.sloth>.accordion
and add a click listener. This means when you click on the selector something will happen, which is defined in the next two lines. - Line 3: When the selector from line 2 is click on, look for the selector
.sloth>article
and add a the classshow
to the '.sloth>article` - Line 4: When the selector from line 2 is click on, look for the selector
.sloth span
and add a the classrotate
to the.sloth span
In the head element add
<script src="scripts.js"></script>
On the first h2 in the three sections with articles add a class="accordion"
.accordion
cursor: pointer;
Hint: This will make the user's cursor into the hand pointing. It is useful to indicate to the user you can click on this element.
article
display none.
We don't want the article to appear at load.
article.show
display block.
When the function is fired and the class of show is added by the javascript to an article element, we now want it to appear with display block.
section span
transform: rotate(180deg);
.
This property will rotate the caret 180 degrees initially, pointing it down. Don't worry about learning the property yet, we will explore it further in a different lab.
span.rotate
transform:rotate(0);
When the rotate class is added by the javascript the caret will rotate to point up.
In the HTML after the iframe add a <a>
with the following
- href https://www.wcs.org/
- target="_blank"
- class="sidelink"
- content "Wildlife Conservation"
.sidelink
background-color #27213C
font color #fff
padding 1rem 2rem
text decoration none
.
Right now it is positioned beneath the header but we want to move it to the right side of the screen. So we are going to use position fixed to do this.
.sidelink
position fixed
transform: rotate(90deg);
z-index 1
Use top and right properties to position the link similar to the image below.
Hint: I used a combination of rem and % to accomplish this.
Looking at the page, the images seem to run together. So let's add a border to the bottom of the images to separate them out.
section>h2
border-bottom 2rem solid #e2512d
Desktop CSS
Add @media (min-width:1000px){}
All CSS from here on will go inside the curly brackets of the media query
.animal-background
height 100rem
top -25%
section>h2
padding 23rem 0
font-size 3rem
background-position center
section span
font-size 4rem
top 26rem
left:calc(50% - 22px);
nav
position absolute.
Hint: Because the header is already position fixed we do not need to add position relative.
Use top and left to position the nav like the image below
article
max-width 60rem
margin 0 auto.
Hint: Remember with width and max-width you can use auto as a value for the left and right on margin to center the element.
Final Steps
Validate your HTML.
- Navigate to W3C Validator
- Select the validate by file upload tab at the top of the page
Lint your CSS at Jigsaw.w3.org
Now look at GitHub Desktop. You should see all of your files listed out in the left column.
Now you are going to commit your changes.
With all of the files checked. Fill out the Summary field in the bottom left and then click Commit to main.
Committing is staging the files, so they can be pushed to the repository hosted at GitHub.
Now you want to push your changes to the Repository. Now if you access the repository from another computer Lab8 will be there. After you push in the top right of the nav it should say "Fetch Origin" instead of "Push Origin"
Your are Done with Lab8
Are you someone who needs to double check that it worked? If you want to make sure the push was successful click on the "View on GitHub" button from GitHub Desktop. It will open up your repository in the browser. From there you should be able to see all of your files.
...What if I need to make a change after pushing?
So let's say you have already pushed but noticed an error. No worries, this is easy to fix.
In visual studio code make any changes you need to. Once you are done making corrections. Save.
Go back to GitHub Desktop. You should see your changes to the documents listed there.
Fill out the Summary field again. I suggest saying what you fixed. For example: "Fixed paragraph error on Sea-Jellies"
Click "Commit to main"
Click "Push Origin" and you are done.