In this lesson, we will explore various CSS techniques to control the layout and positioning of elements on a web page.
Table of Contents
Positioning
Positioning properties in CSS allow you to control the placement of elements on the page. The main positioning properties include:
static
: Default positioning, element flows with the normal document flowrelative
: Positioned relative to its normal positionabsolute
: Positioned relative to its nearest positioned ancestorfixed
: Positioned relative to the browser windowsticky
: Positioned based on the user’s scroll position
Example:
.relative-box {
position: relative;
left: 20px;
top: 10px;
}
.absolute-box {
position: absolute;
right: 30px;
bottom: 40px;
}
.fixed-box {
position: fixed;
top: 0;
right: 0;
}
Display
The display
property in CSS defines how an element should be displayed on the page. Common display values include:
block
: Displays an element as a block element, taking up the full width availableinline
: Displays an element as an inline element, only taking up as much width as necessaryinline-block
: Displays an element as an inline-level block container, allowing control over the width and heightnone
: Hides the element
Example:
.block-element {
display: block;
}
.inline-element {
display: inline;
}
.inline-block-element {
display: inline-block;
width: 200px;
height: 50px;
}
Flexbox
Flexbox is a CSS layout model that allows you to create complex layouts with ease. Key flexbox properties include:
display: flex
: Sets an element as a flex containerflex-direction
: Sets the direction of the flex items (row or column)justify-content
: Aligns flex items along the main axisalign-items
: Aligns flex items along the cross axisflex-wrap
: Allows flex items to wrap onto multiple linesflex
: Sets the flexible size of a flex item
Example:
.flex-container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.flex-item {
flex: 1;
margin: 10px;
}
Actionable Work
- Create an HTML file with a variety of elements that will demonstrate different positioning, display, and flexbox techniques.
- In a separate CSS file, apply various positioning properties to the elements.
- Use different display values to see how the elements behave on the page.
- Create a flex container with multiple flex items, and experiment with the flexbox properties.
- Link your CSS file to your HTML file and preview your work in a web browser to see the effects of positioning, display, and flexbox on the layout.