In this exercise, you will practice using absolute positioning in CSS to position elements on a web page.
Step 1: Create the HTML#
Create a new HTML file and add the following code to create a simple web page. Remember to save the file with the .html
extension. Alternatively, you can use the CodePen editor to create the HTML file. In which case, you can use the CSS window to add your CSS code instead of the style
element in the head
element.
<!DOCTYPE html>
<html>
<head>
<title>Absolute Positioning Practice</title>
<style>
/* Add your CSS code here */
</style>
</head>
<body>
<div class="container">
<div class="box box1">Box 1</div>
<div class="box box2">Box 2</div>
<div class="box box3">Box 3</div>
</div>
</body>
</html>
Step 2: Add CSS for the Container#
Add CSS code to style the container element to have a height of 400 pixels and a background color of light gray.
.container {
height: 400px;
background-color: #eee;
}
Step 3: Add CSS for Static Positioning#
Add CSS code to position the first box using static positioning. The first box should be positioned in the top-left corner of the container.
.box1 {
position: static;
}
Step 4: Add CSS for Absolute Positioning#
Add CSS code to position the second and third boxes using absolute positioning. The second box should be positioned in the bottom-right corner of the container, with a 20-pixel margin from the bottom and right edges. The third box should be positioned in the top-right corner of the container, with a 50-pixel margin from the top and right edges.
.box2 {
position: absolute;
bottom: 20px;
right: 20px;
}
.box3 {
position: absolute;
top: 50px;
right: 50px;
}
Step 5: Test Your Code#
Save your HTML and CSS files and open the HTML file in your web browser to see the results.
You should see three boxes on the page, with the first box positioned in the top-left corner of the container using static positioning. The second box should be positioned in the bottom-right corner of the container using absolute positioning, with a 20-pixel margin from the bottom and right edges. The third box should be positioned in the top-right corner of the container using absolute positioning, with a 50-pixel margin from the top and right edges.
Congratulations! You have successfully completed the exercise and practiced using absolute positioning in CSS.