CSS - Layout using CSS
Box Model
The CSS box model is a basic concept in web design that describes how elements are shown and how their sizes are calculated. Every HTML element is considered a box, and the box model defines how the element's content, padding, border, and margin work with each other.
The box model has four main parts:
Component | Description |
---|---|
Content | The content area is where the actual content of the element, such as text or images, is shown. The size of the content area is set by the width and height properties. |
Padding | The padding is the space between the content and the border of an element. It is used to create spacing within the element itself. You can set the padding using the padding property, which takes values for top, right, bottom, and left padding. |
Border | The border is a line that surrounds the content and padding of an element. It can have a width, style, and color. You can set the border properties using the border shorthand property or individual properties like border-width , border-style , and border-color . |
Margin | The margin is the space outside the border of an element. It is used to create spacing between the element and its neighboring elements. You can set margins using the margin property, which takes values for top, right, bottom, and left margins. |
By default, the size of an element is calculated by adding the content width/height, padding, and border. This means that if you set an element's width to 200 pixels and add 20 pixels of padding and a 2-pixel border, the actual width of the element will be 244 pixels (200px content + 40px padding + 4px border).
To change this behavior and include the padding and border within the set width and height, you can use the box-sizing
property.
box-sizing property example
box-sizing: border-box;
Setting box-sizing: border-box;
tells the browser to include the padding and border in the element's total width and height. This makes it easier to control the size of elements without having to account for extra padding and border sizes.
Knowing the CSS box model is important for creating well-structured and properly spaced layouts. By changing the content, padding, border, and margin of elements, you can control their sizes and positions within the web page.
Display Property
The CSS display
property sets how an element is shown on a web page and how it interacts with other elements. It controls the layout and flow of elements within the document. There are several values for the display
property, each with its own characteristics:
Block-level elements
Block-level elements always start on a new line and take up the full width available by default. They create a new block formatting context and can have margins, padding, and borders applied to them. Some examples of block-level elements are <div>
, <p>
, <h1>
to <h6>
, <ul>
, and <ol>
. You can set an element to be a block-level element using display: block;
.
Block-level example
<div>This is a block-level element.</div>
<p>This is another block-level element.</p>
Inline elements
Inline elements do not start on a new line and only take up as much width as needed for their content. They cannot have a set width, height, or vertical margins, but they can have horizontal margins, padding, and borders. Examples of inline elements include <span>
, <a>
, <em>
, and <strong>
. To make an element an inline element, use display: inline;
.
Inline element example
<span>This is an inline element.</span>
<a href="#">This is another inline element.</a>
Inline-block elements
Inline-block elements are a mix of block-level and inline elements. They flow inline like inline elements but can have a set width, height, and vertical margins like block-level elements. This allows you to create elements that can sit next to each other horizontally while still being able to control their sizes. Use display: inline-block;
to set an element as an inline-block element.
Inline-block example
<div style="display: inline-block;">This is an inline-block element.</div>
<div style="display: inline-block;">This is another inline-block element.</div>
Flex and grid display properties
Flexbox and CSS Grid are two powerful layout systems in CSS that allow you to create flexible and responsive designs.
Flexbox is a one-dimensional layout system that helps you distribute space among items in a container and control their alignment. To create a flex container, use display: flex;
on the parent element. The child elements within the flex container become flex items and can be controlled using flex properties.
Flex container example
<div style="display: flex;">
<div>Flex item 1</div>
<div>Flex item 2</div>
<div>Flex item 3</div>
</div>
CSS Grid is a two-dimensional layout system that allows you to create complex grid-based designs. It lets you define rows and columns and place items within the grid cells. To create a grid container, use display: grid;
on the parent element. The child elements become grid items and can be positioned and sized using grid properties.
Grid container example
<div style="display: grid; grid-template-columns: repeat(3, 1fr);">
<div>Grid item 1</div>
<div>Grid item 2</div>
<div>Grid item 3</div>
</div>
Both Flexbox and CSS Grid are useful tools for creating modern, responsive layouts. They offer more flexibility and control compared to traditional layout methods like floats and positioning.
By using the appropriate display
property values, you can control how elements are shown and how they interact with each other on the web page. This helps in creating well-structured and appealing layouts.
Positioning
The CSS position
property determines how an element is positioned within a web page and how it interacts with other elements around it. It allows you to control the placement and layout of elements in ways that cannot be done using normal document flow. There are five main values for the position
property:
Static positioning
Static positioning is the default positioning for all elements. Elements with position: static;
are not affected by the top
, right
, bottom
, or left
properties. They follow the normal document flow and are positioned based on their order in the HTML.
Example: Static Positioning
<div style="position: static;">
This element has static positioning.
</div>
Relative positioning
An element with position: relative;
is positioned relative to its normal position in the document flow. You can use the top
, right
, bottom
, and left
properties to move the element away from its normal position. The space the element would have taken up in the normal flow is still reserved.
Example: Relative Positioning
<div style="position: relative; top: 20px; left: 30px;">
This element has relative positioning.
</div>
Absolute positioning
An element with position: absolute;
is removed from the normal document flow and positioned relative to its closest positioned ancestor (an ancestor element with a position value other than static
). If no positioned ancestor exists, it is positioned relative to the initial containing block (usually the <html>
element). You can use the top
, right
, bottom
, and left
properties to specify the element's position.
Example: Absolute Positioning
<div style="position: relative;">
<div style="position: absolute; top: 10px; right: 20px;">
This element has absolute positioning.
</div>
</div>
Fixed positioning
An element with position: fixed;
is removed from the normal document flow and positioned relative to the browser window's viewport. It stays in the same position even if the page is scrolled. Like absolute positioning, you can use the top
, right
, bottom
, and left
properties to specify the element's position.
Example: Fixed Positioning
<div style="position: fixed; bottom: 20px; right: 20px;">
This element has fixed positioning.
</div>
Sticky positioning
Sticky positioning is a mix of relative and fixed positioning. An element with position: sticky;
behaves like a relatively positioned element until it reaches a specified threshold (set using the top
, right
, bottom
, or left
properties). Once the threshold is met, the element "sticks" in place and behaves like a fixed positioned element.
Example: Sticky Positioning
<div style="position: sticky; top: 20px;">
This element has sticky positioning.
</div>
Flexbox
Flexbox is a one-dimensional layout system for arranging and distributing space among items in a container. It helps create responsive layouts that adapt to different screen sizes and devices. With flexbox, you can lay out, align, and distribute space among items in a container, even if their sizes are unknown or dynamic.
To create a flex container, apply the display: flex;
property to an element. The child elements within the flex container automatically become flex items and can be controlled using flexbox properties.
Flex container properties
Flex-direction
The flex-direction
property sets the direction of the main axis in a flex container. It determines the direction in which the flex items are laid out. The possible values are:
row
(default): Flex items are laid out in a row from left to right.row-reverse
: Flex items are laid out in a row from right to left.column
: Flex items are laid out in a column from top to bottom.column-reverse
: Flex items are laid out in a column from bottom to top.
Flex-direction example
.flex-container {
display: flex;
flex-direction: row;
}
Flex-wrap
The flex-wrap
property controls whether the flex items should wrap onto multiple lines when there is not enough space in the flex container. The possible values are:
nowrap
(default): Flex items are laid out in a single line, even if they overflow the container.wrap
: Flex items wrap onto multiple lines when there is not enough space.wrap-reverse
: Flex items wrap onto multiple lines in reverse order.
Flex-wrap example
.flex-container {
display: flex;
flex-wrap: wrap;
}
Justify-content
The justify-content
property defines how the flex items are aligned along the main axis of the flex container. It controls the distribution of space between and around flex items. The possible values are:
flex-start
(default): Flex items are packed towards the start of the main axis.flex-end
: Flex items are packed towards the end of the main axis.center
: Flex items are centered along the main axis.space-between
: Flex items are evenly distributed along the main axis, with the first item at the start and the last item at the end.space-around
: Flex items are evenly distributed with equal space around them.space-evenly
: Flex items are evenly distributed with equal space between and around them.
Justify-content example
.flex-container {
display: flex;
justify-content: center;
}
Align-items
The align-items
property defines how the flex items are aligned along the cross axis of the flex container. It controls the alignment of items within each line. The possible values are:
stretch
(default): Flex items stretch to fill the container along the cross axis.flex-start
: Flex items are aligned at the start of the cross axis.flex-end
: Flex items are aligned at the end of the cross axis.center
: Flex items are centered along the cross axis.baseline
: Flex items are aligned based on their baselines.
Align-items example
.flex-container {
display: flex;
align-items: center;
}
Align-content
The align-content
property defines how the flex lines are aligned within the flex container when there is extra space along the cross axis. It only takes effect when there are multiple lines of flex items. The possible values are similar to justify-content
:
stretch
(default): Flex lines stretch to fill the container along the cross axis.flex-start
: Flex lines are packed towards the start of the cross axis.flex-end
: Flex lines are packed towards the end of the cross axis.center
: Flex lines are centered along the cross axis.space-between
: Flex lines are evenly distributed along the cross axis, with the first line at the start and the last line at the end.space-around
: Flex lines are evenly distributed with equal space around them.space-evenly
: Flex lines are evenly distributed with equal space between and around them.
Align-content example
.flex-container {
display: flex;
flex-wrap: wrap;
align-content: space-between;
}
Flex item properties
Order
The order
property sets the order in which a flex item appears within the flex container. By default, flex items are displayed in the order they appear in the source code. The order
property allows you to change this order. It takes an integer value, and flex items with a lower value appear before those with a higher value.
Order example
.flex-item {
order: 2;
}
Flex-grow
The flex-grow
property determines how much a flex item should grow relative to other flex items when there is extra space in the flex container. It takes a non-negative number as a value. By default, it is set to 0, which means the item will not grow.
Flex-grow example
.flex-item {
flex-grow: 1;
}
Flex-shrink
The flex-shrink
property determines how much a flex item should shrink relative to other flex items when there is not enough space in the flex container. It takes a non-negative number as a value. By default, it is set to 1, which means the item will shrink proportionally with other items.
Flex-shrink example
.flex-item {
flex-shrink: 0;
}
Flex-basis
The flex-basis
property sets the initial size of a flex item before any growing or shrinking occurs. It can be a length value (e.g., pixels or percentages) or the keyword auto
(default). When set to auto
, the item's size is based on its content.
Flex-basis example
.flex-item {
flex-basis: 200px;
}
Align-self
The align-self
property allows you to override the alignment of an individual flex item along the cross axis. It takes the same values as align-items
(stretch
, flex-start
, flex-end
, center
, baseline
) but applies to a single flex item instead of all items in the container.
Align-self example
.flex-item {
align-self: flex-end;
}
By using these flexbox properties, you can create flexible and responsive layouts that adapt to different screen sizes and content needs. Flexbox provides a toolset for building modern web layouts with ease and flexibility.
CSS Grid
CSS Grid is a two-dimensional layout system that lets you create complex and responsive grid-based designs. It provides a way to define rows and columns in a container and place and size items within the grid cells. CSS Grid gives you control over the layout of your web pages, making it easier to create designs that adapt to different screen sizes.
To create a grid container, apply the display: grid;
property to an element. The child elements within the grid container become grid items and can be positioned and sized using CSS Grid properties.
Grid Container Properties
Property | Description |
---|---|
grid-template-columns and grid-template-rows |
Define the size and number of columns and rows in a grid container. You can specify the size using length values (e.g., pixels or percentages), the fr unit (which represents a fraction of the available space), or a combination of both. |
grid-template-areas |
Allows you to define a grid template using named grid areas. You can create a visual representation of your grid layout using a string syntax, where each row is represented by a space-separated list of area names, and each column is separated by a space. |
grid-gap |
Sets the size of the gaps (gutters) between grid rows and columns. It is a shorthand property for grid-row-gap and grid-column-gap . You can specify the gap size using length values. |
justify-items and align-items |
Control how grid items are aligned within their grid cells along the row and column axes. They can take values such as start , end , center , and stretch (default). |
justify-content and align-content |
Control the alignment and distribution of the grid tracks (rows and columns) within the grid container. They can take values such as start , end , center , stretch , space-between , space-around , and space-evenly . |
Grid Item Properties
Property | Description |
---|---|
grid-column and grid-row |
Allow you to specify the size and location of a grid item within the grid. You can use the start and end values to define the starting and ending grid lines for an item. |
grid-area |
Allows you to assign a name to a grid item, which can then be referenced in the grid-template-areas property of the grid container. It provides a way to place items within the grid using named areas. |
justify-self and align-self |
Allow you to control the alignment of an individual grid item within its grid cell. They override the justify-items and align-items values set on the grid container for a specific item. They can take the same values as justify-items and align-items . |
Grid-template-columns and Grid-template-rows example
.grid-container {
display: grid;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: 100px auto;
}
Grid-template-areas example
.grid-container {
display: grid;
grid-template-areas:
"header header header"
"sidebar content content"
"footer footer footer";
}
Grid-gap example
.grid-container {
display: grid;
grid-gap: 20px;
}
Justify-items and Align-items example
.grid-container {
display: grid;
justify-items: center;
align-items: end;
}
Justify-content and Align-content example
.grid-container {
display: grid;
justify-content: space-between;
align-content: center;
}
Grid-column and Grid-row example
.grid-item {
grid-column: 1 / 3;
grid-row: 2 / 4;
}
Grid-area example
.grid-item {
grid-area: header;
}
Justify-self and Align-self example
.grid-item {
justify-self: end;
align-self: center;
}
Floats
Floating elements is a CSS technique that allows elements to be removed from the normal document flow and positioned to the left or right of their containing element. Floats are used for wrapping text around images or creating multi-column layouts.
To float an element, use the float
property with a value of left
or right
. When an element is floated, it is taken out of the normal document flow, and other elements will flow around it.
Example: Floating an Image
<img src="image.jpg" style="float: left;">
<p>This is some text that will wrap around the floated image.</p>
When using floats, it's important to consider how they affect the layout of the surrounding elements. Floated elements can cause their containing element to collapse if not properly cleared. This is because floated elements are removed from the normal document flow, and the containing element may not have any other content to give it height.
To fix this issue, you need to clear the floats. Clearing floats means telling the browser where the floating elements end, and the normal document flow should resume. There are several techniques for clearing floats:
Technique | Description | Example |
---|---|---|
Clear property | Apply the clear property to an element that comes after the floated elements. The clear property accepts values of left , right , or both , indicating which side of the floating elements should be cleared. |
<div style="clear: both;"></div> |
Clearfix hack | Apply a class (often named "clearfix") to the containing element of the floated elements. The clearfix hack uses pseudo-elements (:before and :after ) to add empty content and clear the floats. |
.clearfix::after { content: ""; display: table; clear: both; } |
Overflow property | Set the overflow property of the containing element to auto or hidden . This creates a new block formatting context, and the containing element will expand to contain the floated elements. |
.container { overflow: auto; } |
When working with floats, it's also important to consider how to contain them within their parent element. If the floated elements are taller than the containing element, they may overflow outside of it. To prevent this, you can use techniques like the clearfix hack or setting a specific height or min-height on the containing element.
Example: Containing Floated Elements
<div style="overflow: auto;">
<img src="image.jpg" style="float: left;">
<p>This is some text that will wrap around the floated image.</p>
</div>
While floats have been widely used for creating layouts in the past, modern CSS layout techniques like flexbox and grid are generally recommended for more flexible and responsive designs. However, understanding how floats work is still valuable for working with older codebases or specific layout requirements.
Responsive Layout
Responsive layout is a key part of modern web design that lets websites adapt and give a good viewing experience across different devices and screen sizes. With the growing range of devices used to access the internet, it's important to create layouts that are flexible and can adjust to different screen resolutions and orientations. CSS provides useful tools and techniques to create responsive layouts, including media queries, flexbox, and CSS grid.
Media Queries
Media queries are a basic tool for creating responsive designs. They let you apply different CSS styles based on the features of the device or viewport, such as screen width, height, orientation, or resolution. By using media queries, you can customize your layout and styles to specific breakpoints, making sure that your website looks and works well on different devices.
Example: Media query that applies different styles for small screens
@media screen and (max-width: 600px) {
.container {
width: 100%;
padding: 10px;
}
.navbar {
display: none;
}
}
When the screen width is 600 pixels or less, the .container
element will have a width of 100% and less padding, and the .navbar
element will be hidden.
Media queries can be used to change various aspects of your layout, such as changing font sizes, moving elements, showing or hiding content, and changing the layout structure based on the available screen space.
Responsive Flexbox Layout
Flexbox is a useful layout system that lets you create flexible and responsive designs easily. By using flexbox, you can create layouts that automatically adjust to different screen sizes without the need for complex media queries.
Example: Responsive flexbox layout
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.item {
flex: 1 1 300px;
margin-bottom: 20px;
}
The .container
element is set to display: flex
and flex-wrap: wrap
, allowing the flex items to wrap onto multiple lines when there isn't enough space. The justify-content: space-between
property spreads the available space evenly between the items.
The .item
elements have a flex
property with values 1 1 300px
, which means they will grow and shrink equally and have a base width of 300 pixels. This makes sure that the items will adjust their size based on the available space while keeping a minimum width.
As the screen size changes, the flex items will automatically wrap and adjust their widths to fit the available space, creating a responsive layout without the need for media queries.
Responsive Grid Layout
CSS grid is another useful layout system that lets you create responsive grid-based designs. With CSS grid, you can define flexible grid structures that adapt to different screen sizes and device capabilities.
Example: Responsive grid layout
<div class="grid-container">
<div class="grid-item">Item 1</div>
<div class="grid-item">Item 2</div>
<div class="grid-item">Item 3</div>
<div class="grid-item">Item 4</div>
</div>
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
}
.grid-item {
background-color: #f1f1f1;
padding: 20px;
}
The .grid-container
element is set to display: grid
, creating a grid container. The grid-template-columns
property uses the repeat()
function with auto-fit
and minmax()
to create a responsive grid structure.
The repeat(auto-fit, minmax(200px, 1fr))
syntax creates a grid with columns that automatically fit the available space. The minmax(200px, 1fr)
value makes sure that each grid item has a minimum width of 200 pixels and will grow equally to fill the remaining space.
As the screen size changes, the grid items will automatically rearrange and adjust their sizes to fit the available space, creating a responsive grid layout without the need for media queries.
By combining media queries, flexbox, and CSS grid, you can create highly responsive and adaptive layouts that provide a good user experience across various devices and screen sizes. These techniques let you design websites that seamlessly adapt to different viewport dimensions, making sure that your content is accessible and looks good on desktops, tablets, and mobile devices.