Hi coding cadets! Ready to learn how to manipulate space?
This post will show you how to use the float, position, and flexbox CSS properties to shape the layout of your web page.
And to take things to a whole other level, we then move on to z-index and opacity.
Make sure to stay until the end to take the challenge! It’s all about creating your very own cover overlay.
CSS Float Property
The CSS float property allows you to change the positionality (left or right) of HTML elements.
Text and inline elements wrap around the floated element as it is removed from the normal flow of the page.
If you float elements in the same direction, they will end up next to each other.
Example: How do you float a box in CSS?
- Create 4 boxes, each a different color. The result should be 4 multi-colored tiles running down your browser page.
<div id="red"></div>
<div id="green"></div>
<div id="blue"></div>
<div id="yellow"></div>
#red { background-color: red;
width: 200px;
height: 200px;
}
#green {
background-color: green;
width: 200px;
height: 200px;
}
#blue {
background-color: blue;
width: 200px;
height: 200px;
}
#yellow {
background-color: yellow;
width: 200px;
height: 200px;
}
- Starting with the second box, float all boxes left because we want to place the boxes next to each other to recreate our tiles, only horizontally instead of vertically.
Hint: Use
float: left;
in your CSS.
If an element(s) isn’t floated, it will place itself in the normal flow of the page which is determined by any floated elements on the page and their respective widths.
This is why in the box example above, we floated the first box left even though it’s already positioned at our starting point.
Had we not done that, the <div>
would have taken up the entire line as divs are block elements.
The floated elements would then take up the rest of the empty space – in this case, the next line. See the example below for visual reference.
How do you clear floats in CSS?
Add a pink circle to your page with a height and width of 400 pixels and notice what happens.
<div id="pink"></div>
#pink {
background-color: pink;
width: 400px;
height: 400px;
border-radius: 50%;
}
Since the pink circle is taking up space based on the normal flow of the page, it lies underneath the floated elements.
To work on the next line without interfering with floated elements (aka get back to the normal flow of the page), you need to clear the float.
Use a <div>
right after the floated objects with the CSS clear property set as both for an element to appear underneath all floated elements.
<div class="clear-float"></div>
.clear-float {
clear: both;
}
CSS Position Property
The CSS position property helps you set the location of an element and is more precise than floating as it creates margins.
Usually, position takes the values relative, absolute, or fixed.
What is the difference between positions in CSS?
To illustrate the different positions, we will be using a circle inside of a square.
<div id="red">
<div id="pink"></div>
</div>
#red {
background-color: red;
width: 500px;
height: 500px;
}
#pink {
background-color: pink;
width: 200px;
height: 200px;
border-radius: 50%;
}
You should start off each time with something like this:
Relative Position
An element is positioned relative to where it’s located followed by a direction, such as top, left, right, and bottom, indicated by pixels.
Direction | Element is shifted… |
---|---|
top | from the top edge down the page |
bottom | from the bottom edge up the page |
left | from the left edge to the right of the page |
right | from the right edge to the left of the page |
Example:
example {
position: relative;
top: 10px;
left: 20px;
}
Challenge
Center the circle in the square. This might prove to be more challenging than you think at first glance.
Careful, don’t do this:
TIP 🤓
Remember, the directions apply to the edge of the shape. So halfway of a square with a width and height of 500px might be 250px either way, but the circle has a width and height of 200px. To get the circle’s center at the center of the square you need to do 250px – 100px = 150px. That can be 150px for either top and left or bottom and right – your choice.
#pink {
background-color: pink;
width: 200px;
height: 200px;
border-radius: 50%;
position: relative;
top: 150px;
left: 150px;
}
Absolute Position
Takes an object out of the flow of the page so it goes over top of everything else.
Example: Add some content to our box to see absolute positioning in practice.
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Feugiat in fermentum posuere urna nec tincidunt praesent semper. Consectetur purus ut faucibus pulvinar elementum integer enim neque volutpat. Viverra mauris in aliquam sem fringilla. Nisl suscipit adipiscing bibendum est ultricies integer quis auctor. Dictum fusce ut placerat orci nulla. Id donec ultrices tincidunt arcu non sodales. Viverra suspendisse potenti nullam ac tortor vitae purus faucibus. Eget mi proin sed libero enim sed faucibus turpis in. Vulputate odio ut enim blandit volutpat maecenas. Tincidunt praesent semper feugiat nibh sed. Ut porttitor leo a diam sollicitudin tempor id. Ornare suspendisse sed nisi lacus sed viverra tellus. Eget est lorem ipsum dolor sit amet. Neque convallis a cras semper auctor. Purus in mollis nunc sed. Ultricies tristique nulla aliquet enim tortor at auctor. Euismod elementum nisi quis eleifend quam adipiscing vitae proin. Risus nec feugiat in fermentum posuere urna nec tincidunt praesent. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien et.
Sed viverra tellus in hac habitasse platea dictumst vestibulum rhoncus. Mauris sit amet massa vitae tortor condimentum lacinia quis. Vitae aliquet nec ullamcorper sit amet risus nullam eget felis. Nisl suscipit adipiscing bibendum est ultricies. Viverra aliquet eget sit amet tellus cras adipiscing enim eu. Fusce ut placerat orci nulla pellentesque dignissim. Accumsan tortor posuere ac ut consequat semper viverra nam libero. Leo urna molestie at elementum eu. Leo vel fringilla est ullamcorper eget nulla facilisi etiam dignissim. Cras semper auctor neque vitae tempus quam pellentesque nec nam. Et tortor consequat id porta nibh venenatis cras sed. Neque aliquam vestibulum morbi blandit cursus risus.
</p>
#pink { background-color: pink;
width: 200px;
height: 200px;
border-radius: 50%;
position: absolute;
top: 100px;
left: 250px;
}
Fixed Position
Like in absolute, the object is taken out of the flow of the page, but, unlike in absolute, the object stays in position even when the page is scrolled.
Example: Make the content longer (we copied the same paragraphs again, no shame in that) so they become scrollable.
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Feugiat in fermentum posuere urna nec tincidunt praesent semper. Consectetur purus ut faucibus pulvinar elementum integer enim neque volutpat. Viverra mauris in aliquam sem fringilla. Nisl suscipit adipiscing bibendum est ultricies integer quis auctor. Dictum fusce ut placerat orci nulla. Id donec ultrices tincidunt arcu non sodales. Viverra suspendisse potenti nullam ac tortor vitae purus faucibus. Eget mi proin sed libero enim sed faucibus turpis in. Vulputate odio ut enim blandit volutpat maecenas. Tincidunt praesent semper feugiat nibh sed. Ut porttitor leo a diam sollicitudin tempor id. Ornare suspendisse sed nisi lacus sed viverra tellus. Eget est lorem ipsum dolor sit amet. Neque convallis a cras semper auctor. Purus in mollis nunc sed. Ultricies tristique nulla aliquet enim tortor at auctor. Euismod elementum nisi quis eleifend quam adipiscing vitae proin. Risus nec feugiat in fermentum posuere urna nec tincidunt praesent. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien et.
Sed viverra tellus in hac habitasse platea dictumst vestibulum rhoncus. Mauris sit amet massa vitae tortor condimentum lacinia quis. Vitae aliquet nec ullamcorper sit amet risus nullam eget felis. Nisl suscipit adipiscing bibendum est ultricies. Viverra aliquet eget sit amet tellus cras adipiscing enim eu. Fusce ut placerat orci nulla pellentesque dignissim. Accumsan tortor posuere ac ut consequat semper viverra nam libero. Leo urna molestie at elementum eu. Leo vel fringilla est ullamcorper eget nulla facilisi etiam dignissim. Cras semper auctor neque vitae tempus quam pellentesque nec nam. Et tortor consequat id porta nibh venenatis cras sed. Neque aliquam vestibulum morbi blandit cursus risus.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Feugiat in fermentum posuere urna nec tincidunt praesent semper. Consectetur purus ut faucibus pulvinar elementum integer enim neque volutpat. Viverra mauris in aliquam sem fringilla. Nisl suscipit adipiscing bibendum est ultricies integer quis auctor. Dictum fusce ut placerat orci nulla. Id donec ultrices tincidunt arcu non sodales. Viverra suspendisse potenti nullam ac tortor vitae purus faucibus. Eget mi proin sed libero enim sed faucibus turpis in. Vulputate odio ut enim blandit volutpat maecenas. Tincidunt praesent semper feugiat nibh sed. Ut porttitor leo a diam sollicitudin tempor id. Ornare suspendisse sed nisi lacus sed viverra tellus. Eget est lorem ipsum dolor sit amet. Neque convallis a cras semper auctor. Purus in mollis nunc sed. Ultricies tristique nulla aliquet enim tortor at auctor. Euismod elementum nisi quis eleifend quam adipiscing vitae proin. Risus nec feugiat in fermentum posuere urna nec tincidunt praesent. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien et.
Sed viverra tellus in hac habitasse platea dictumst vestibulum rhoncus. Mauris sit amet massa vitae tortor condimentum lacinia quis. Vitae aliquet nec ullamcorper sit amet risus nullam eget felis. Nisl suscipit adipiscing bibendum est ultricies. Viverra aliquet eget sit amet tellus cras adipiscing enim eu. Fusce ut placerat orci nulla pellentesque dignissim. Accumsan tortor posuere ac ut consequat semper viverra nam libero. Leo urna molestie at elementum eu. Leo vel fringilla est ullamcorper eget nulla facilisi etiam dignissim. Cras semper auctor neque vitae tempus quam pellentesque nec nam. Et tortor consequat id porta nibh venenatis cras sed. Neque aliquam vestibulum morbi blandit cursus risus.
</p>
#red {
background-color: red;
width: 500px;
height: auto;
}
#pink {
background-color: pink;
width: 200px;
height: 200px;
border-radius: 50%;
position: fixed;
top: 100px;
left: 250px;
}
NOTE: The height of the red square changed from 500px to auto so that our content stays inside the box.
What’s the difference between absolute and fixed positions in CSS?
Notice how changing the position to absolute leads the element to go out of view when scrolling the page.
However, once you change the position to fixed, the element stays in view on scroll.
Layering HTML elements with CSS: Z-index and Opacity
What is z-index in CSS?
For layering, use the CSS z-index property after indicating positionality.
What are the values of z-index?
The z-index takes a value from negative to positive integers – it defaults to 0. Big numbers designate elements on top of other elements whereas small numbers designate elements beneath other elements.
(Yeah, yeah but what does this even MEAN? – DM)
To answer DM’s question, let’s have 3 squares – red, yellow, blue – each with a respective z-index of 5, -2, -5.
<div id="red"></div>
<div id="yellow"></div>
<div id="blue"></div>
#red {
background-color: red;
width: 200px;
height: 200px;
}
#yellow {
background-color: yellow;
width: 200px;
height: 200px;
}
#blue {
background-color: blue;
width: 200px;
height: 200px;
}
Shift the yellow and blue square upwards by 100px. Remember the blue square will actually shift by 200px since it goes up 100px by itself + the 100px of the yellow square!
Hint: Use a relative position with a negative top direction because we are pulling the top edge of the element up the page.
#yellow {
background-color: yellow;
width: 200px;
height: 200px;
position: relative;
top: -100px;
}
#blue {
background-color: blue;
width: 200px;
height: 200px;
position: relative;
top: -200px;
}
You should now have 3 overlapping squares. Assign the z-indexes (red as 5, yellow as -2, and blue as -5).
See how the stacking order changes? The yellow square doesn’t make it that obvious since it’s in the middle, but we now have the entire red square showing instead of the blue one.
#red {
background-color: red;
width: 200px;
height: 200px;
z-index: 5;
}
#yellow {
background-color: yellow;
width: 200px;
height: 200px;
position: relative;
top: -100px;
z-index: -2;
}
#blue {
background-color: blue;
width: 200px;
height: 200px;
position: relative;
top: -200px;
z-index: -5;
}
In the case of overlapping elements, the element with the highest indicated z-index number goes on top.
Now, let’s take a look at opacity.
The CSS opacity property determines how see-through an object is using a range of 0 – 1 where 0 is completely see-through and 1 is solid.
Give the red square an opacity of 0.2 and the yellow square of 0.4.
#red {
background-color: red;
width: 200px;
height: 200px;
z-index: 5;
opacity: 0.2;
}
#yellow {
background-color: yellow;
width: 200px;
height: 200px;
position: relative;
top: -100px;
z-index: -2;
opacity: 0.4;
}
You can now see the portion of the yellow square under the red one and that of the blue square under the yellow one.
When used together with z-index, opacity makes for a powerful and effective visual presentation of layering objects on a web page.
Flexbox
CSS flexbox allows for the distribution of space in a container without using float or positioning.
First, set the display to flex for a wrapping container then you can set:
Flex-direction | Determines axis |
---|---|
justify-content | Horizontal (main-axis) alignment |
flex-wrap | Element moves to new column/row instead of fitting-in |
align-items | Distribute space along the cross axis (vertical direction) |
align-content | Controls space between rows/columns only when flex-wrap is specified |
There are more flex properties to explore than the ones listed here, but this is a good start.
As practice copy the code for creating 4 boxes from the How do you float a box in CSS? section above.
Once again, let’s arrange the colored squares horizontally across the page. Only this time, we will use flexbox instead of float.
- Wrap the squares in a container with display set as flex.
- Set the flex-direction to row.
Cover Overlay Using HTML and CSS
Challenge
Create a cover overlay with a text quote in the center.
Your finished product should look something like this:
Try it on your own, then check your work against the steps below. Good luck!
Challenge coding solution:
<div id="cover">
<div id="column">
<h1>You set your own limits in life.</h1>
<div id="flex-container">
<h3>- THT</h3>
</div>
</div>
</div>
- Get rid of default margins and/or padding from the body so our overlay takes on the full width and height of the window.
body {
margin: 0;
padding: 0;
}
- Add a background image, center and make it slightly opaque. Give it a full view height so it takes up the entire window. Lastly, make the text white and center it.
#cover {
background-image: url('https://images.unsplash.com/photo- 1444703686981-a3abbc4d4fe3?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=870&q=80');
background-size: cover;
background-position: center;
opacity: 0.7;
color: white;
height: 100vh;
text-align: center;
}
- Use flexbox to align the citation on the right-hand corner of its container. Center that container by setting its margin left and right to auto.
Note: This is one way of doing this, you don’t need to use flexbox but might as well get in some practice.
#flex-container {
display: flex;
flex-direction: row-reverse;
width: 40%;
margin: 0 auto;
}
- Add padding at the top on the column container to bring the text further down the page.
#column {
padding-top: 100px;
}
- Make the text bigger and change the font-family to a non-serif type.
h1, h3 {
font-size: 400%;
font-family: Arial, Helvetica, sans-serif;
}
Success! You just created a cover overlay from scratch. How easy was that?