CSS Properties
CSS is constantly evolving under the guidance of the W3C, and they ensure regular updates and releases of new modules. However, it can sometimes be challenging to determine which properties can be safely used. This is because new browsers may implement a property long before it becomes a W3C REC (Recommendation).
All properties from REC (Recommendation) modules can be used without any issues. You can get an overview of other modules on https://www.caniuse.com (for example, sticky). However, please note that the approval of a property on caniuse.com does not necessarily mean that the properties are implemented, so it’s always advisable to conduct tests, possibly using sites like BrowserStack.
In summary, it’s essential to stay updated on CSS properties and their compatibility with various browsers to ensure a consistent and reliable user experience across different platforms.
Understanding CSS Properties
CSS properties define how elements on a webpage are styled and behave. Each CSS property consists of a property name and a value, separated by a colon. The property name specifies the aspect of the element that you want to style, such as color or font-size, while the value provides the specific style to apply, like red or 16px.
Using Shorthand Properties
CSS also allows you to use shorthand properties to define multiple related styles in a single line. For example, the margin property can set all four sides (top, right, bottom, and left) at once:
instead of:
/* Example of individual properties */
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;
Shorthand properties can simplify your CSS and make it more readable, but use them with care. Ensure that you understand the order and default values they imply, as it can sometimes lead to unexpected results.
Text Properties
There are numerous properties related to text styling in CSS that allow for extensive control over typography and layout.
Fonts
You can specify fonts for your text using the font-family property. If a specific font is not available, the browser will fall back to other, more general fonts listed in the font-family declaration.
It’s important to list fallback fonts in case the primary font is unavailable. The browser will use the first available font in the list.
External Fonts
In addition to the internal fonts provided by the browser, you can also use external fonts. Common formats include:
- WOFF (Web Open Font Format)
- TrueType
You can obtain these fonts from various sources, such as Google Fonts. To use an external font, you can define it with the @font-face rule:
@font-face {
font-family: "Shadows Into Light";
font-style: normal;
font-weight: 400;
src: local("Shadows Into Light"), local("ShadowsIntoLight"),
url(https://fonts.gstatic.com/s/shadowsintolight/v7/UqyNK9UOIntux_czAvDQx_ZcHqZXBNQzdcD5.woff2)
format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6,
U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193,
U+2212, U+2215, U+FEFF, U+FFFD;
}
p {
font-family: "Shadows Into Light", sans-serif;
}
Text Alignment and Decoration
text-align: Aligns the text within its container. Options includeleft,right,center, andjustify.
text-decoration: Adds decoration to the text, such asunderline,overline,line-through, ornone.
text-transform: Controls the capitalization of text. Options includeuppercase,lowercase, andcapitalize.
These properties allow for precise control over the appearance and behavior of text in your web design, ensuring that your content is both readable and visually appealing.
Size
Size in CSS is a versatile property that applies not only to text but also to boxes, margins, padding, and various other elements. You can specify size using different units, each serving a distinct purpose:
px(pixels): An absolute unit that represents a fixed size on the screen.%(percentage): A relative unit that scales based on the size of the parent element.em(relative to the parent): A relative unit where the size is calculated based on the font size of the parent element. If the parent has afont-sizeof16px, then1emequals16px.rem(relative to the root): Similar toem, but the size is relative to the root element (<html>), making it consistent across different elements regardless of nesting.pt(points): A unit traditionally used in print, equal to 1/72 of an inch. It is less commonly used in web design.vw(viewport width): A relative unit based on the width of the viewport.1vwequals 1% of the viewport’s width.
In the context of text, px and em/rem are the most commonly used units:
Choosing the right unit depends on your design goals. Pixels are ideal for fixed, pixel-perfect layouts, while em and rem are better suited for responsive designs that need to adapt to various devices and screen sizes.
Style
CSS provides a wide range of properties to style text, allowing for detailed control over the appearance and layout of text content. Below is an overview of the most commonly used text styling properties:
Font Style
font-style: Controls the style of the text. Common values include:normal: Default text style.italic: Italicized text.oblique: A slanted version of the text (similar to italic but less commonly used).
Font Weight
font-weight: Adjusts the boldness of the text. Common values include:normal: Default weight.bold: Bold text.- Numerical values (
100to900): Specifies the thickness, with higher numbers indicating bolder text.
Font Variant
font-variant: Changes the text to small-caps or other variants. Common values include:normal: Default text variant.small-caps: Transforms lowercase text to uppercase, but with smaller, capitalized letters.
Text Transform
text-transform: Controls the capitalization of text. Available options:none: Default text style.capitalize: Capitalizes the first letter of each word.uppercase: Converts all text to uppercase.lowercase: Converts all text to lowercase.
Text Decoration
text-decoration: Adds decorations to the text. Common values include:none: No decoration (default).underline: Underlines the text.overline: Adds a line above the text.line-through: Strikes through the text.
Text Shadow
text-shadow: Adds a shadow effect to the text. It accepts four values:h-shadow: Horizontal shadow (offset from the text).v-shadow: Vertical shadow (offset from the text).blur: Optional; controls the blur radius of the shadow.color: Specifies the color of the shadow.
here is another
This example creates a black shadow slightly down and to the right, and a red shadow up and to the left.
Text Alignment
text-align: Aligns the text within its container. Possible values include:left: Aligns text to the left.center: Centers the text.right: Aligns text to the right.justify: Stretches the text so that each line has equal width.
Vertical Alignment
vertical-align: Aligns text vertically relative to its containing element. Useful in inline or table-cell elements. Common values include:baseline: Aligns with the baseline of the parent element (default).top: Aligns the text to the top of the container.middle: Centers the text vertically within the container.bottom: Aligns the text to the bottom of the container.
Letter Spacing
letter-spacing: Adjusts the space between characters in the text. The value is usually specified inpxorem.
Word Spacing
word-spacing: Controls the space between words in the text. Typically specified inpxorem.
Line Height
line-height: Specifies the height of a line of text. It can be a unitless number, percentage, or length (e.g.,1.5,150%,20px). Adjusting line height is crucial for improving readability.
Example
Here’s an example that combines several of these styling properties:
.special {
font-style: italic;
font-weight: bold;
text-transform: uppercase;
text-decoration: underline;
text-shadow: 4px 4px 4px red;
}
This rule set styles the text with an italic, bold, and uppercase appearance, underlines it, and adds a red shadow.
Columns
Dividing text into multiple columns is a powerful feature that allows for more magazine-like layouts on the web. This functionality is easily achieved using the columns property, which is widely supported in modern browsers.
The columns property is a shorthand for setting both column-count and column-width in one declaration:
column-count: Specifies the number of columns the content should be split into.column-width: Defines the ideal width for each column. The browser will create as many columns of at least this width as possible within the container.
You can also control the spacing between columns using the column-gap property, which sets the space between each column.
Example:
columns: 4: Splits the content inside thediv#colelement into 4 evenly spaced columns.column-gap: 20px: Sets a20pxgap between each column to ensure the text doesn’t appear too cramped.
This approach automatically balances the content across the columns, making it an efficient way to present long text in a more digestible, multi-column format.
Additional Column Properties
Here are some additional properties that you can use to further customize your column layouts:
column-width: Instead of specifying a fixed number of columns, you can define the width of each column. The browser will then determine the appropriate number of columns based on the container’s width.
column-rule: Adds a rule (line) between columns. This property is shorthand forcolumn-rule-width,column-rule-style, andcolumn-rule-color.
column-span: Allows an element to span across all columns. For example, a heading could stretch across the entire width, with the content below it divided into columns.
Using these properties, you can create sophisticated, flexible layouts that enhance the readability and aesthetic appeal of your web pages.
Colors
Color is an essential part of web design, affecting both the aesthetic and usability of a site. CSS offers a variety of properties to control the color of text, backgrounds, borders, and other elements.
Text Colors
color: Sets the color of the text.background-color: Defines the background color of an element.text-shadow: Adds shadow effects to the text, which can be used to enhance readability or create visual interest.
Box Colors
box-shadow: Applies shadow effects around the element’s frame, which can add depth and a sense of layering.border-color: Sets the color of an element’s border.
Specifying Colors
CSS allows you to specify colors in several different formats, each offering flexibility for different design needs:
- By Name: CSS supports a wide range of predefined color names.
-
Examples:
blue,red,green. -
By Hexadecimal (
hex): A six- or eight-digit code representing the amount of red, green, and blue in a color, optionally including an alpha channel for transparency. -
Examples:
#ff0000(red),#0000ff(blue),#ff000080(semi-transparent red). -
By RGB: Defines colors using the Red, Green, Blue color model, with optional alpha transparency.
-
Examples:
rgb(255, 0, 0)(red),rgb(0, 0, 255)(blue). -
By HSL: Specifies colors using the Hue, Saturation, Lightness model, also with optional alpha transparency.
- Examples:
hsl(120, 100%, 50%)(a pure green),hsl(120, 60%, 70%)(a lighter green).
Examples
Here’s an example demonstrating the use of different color formats in CSS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Color Demo</title>
<style>
h1:nth-child(1) {
color: red; /* Color by name */
}
h1:nth-child(2) {
color: rgb(0, 0, 255); /* Color by RGB */
}
h1:nth-child(3) {
color: hsl(120, 100%, 50%); /* Color by HSL */
}
</style>
</head>
<body>
<h1>Test</h1>
<h1>Test</h1>
<h1>Test</h1>
</body>
</html>
In this example:
- The first heading (h1) uses a named color (red).
- The second heading uses an RGB color (rgb(0, 0, 255)), which results in a blue color.
- The third heading uses an HSL color (hsl(120, 100%, 50%)), producing a vivid green.
By understanding and utilizing these different methods of specifying colors, you can achieve precise control over the visual styling of your web content.
Box Model
The CSS Box Model is a foundational concept that describes how elements on a webpage are structured and rendered. Every block-level element in HTML, such as <div>, <p>, and <h1>, is considered a “box” that takes up space on the page. Understanding the box model is crucial for effective web design, as it helps you control the layout, spacing, and size of elements.
+---------------------------+
| margin |
| +---------------------+ |
| | border | |
| | +---------------+ | |
| | | padding | | |
| | | +-----------+ | | |
| | | | content | | | |
| | | +-----------+ | | |
| | +---------------+ | |
| +---------------------+ |
+---------------------------+
Components of the Box Model
The box model consists of several key properties that determine the size and spacing of an element. These properties are applied in the following order from the inside out:
- Content: The innermost area where the text, images, or other media reside.
- Padding: The space between the content and the border. It increases the size of the box but does not affect the distance between boxes.
- Border: The line that surrounds the padding (if any) and the content. The thickness and style of the border can be customized.
- Margin: The outermost space that separates the element from surrounding elements. Unlike padding, margins create space outside the border.
Box Model Properties
Here’s a breakdown of the key CSS properties that control the box model:
widthandheight: Define the size of the content area. By default, these properties set the width and height of the content inside the padding, border, and margin.
padding: Specifies the space between the content and the border. Padding can be set uniformly for all sides or individually for each side (padding-top,padding-right,padding-bottom,padding-left).
border: Defines the border surrounding the padding and content. You can customize the border’s width, style, and color. Like padding, borders can be set uniformly or for each side individually.
div#box {
border: 1px solid black; /* uniform border */
border-top: 2px dashed red; /* top border only */
}
margin: Specifies the space outside the border, separating the element from other elements. Like padding, margins can be set uniformly or individually for each side.
max-width: Limits the maximum width of the content area. This is useful for creating responsive designs, ensuring that elements do not exceed a certain width even on larger screens.
border-radius: Rounds the corners of the border. The value can be set as a percentage or pixel value. A value of50%will create a circular shape if the width and height are equal.
box-shadow: Adds shadow effects around the element’s box. You can define the horizontal and vertical offsets, blur radius, spread radius, and shadow color.
Example of a Box Model in Action
div#box {
width: 100px;
height: 100px;
background-color: yellow;
border: 1px solid black;
padding: 5px;
margin: 5px;
border-radius: 10px;
box-shadow: 10px 10px 10px black;
}
In this example:
- The content area is 100px by 100px.
- The padding adds 5px of space inside the border.
- The border is 1px thick and solid black.
- The margin adds 5px of space outside the border.
- The corners of the border are rounded with a 10px radius.
- The box has a shadow that is 10px offset horizontally and vertically, with a 10px blur radius.
Background Images and Colors
In addition to the basic box model properties, you can enhance the appearance of an element by adding background images and colors. Background properties allow you to control how images are displayed inside the element’s box.
Background Image
You can apply a background image to a box using the background-image property. Additional properties like background-size, background-repeat, and background-position allow you to control the appearance of the image.
#myDiv {
background-image: url('https://cdn.pixabay.com/photo/2015/07/09/22/45/tree-838667_1280.jpg');
background-size: cover;
background-repeat: no-repeat;
background-position: center;
height: 300px;
width: 300px;
background-color: #f3f3f3; /* Fallback color */
}
In this example:
- background-image: Specifies the image URL.
- background-size: cover: Scales the image to cover the entire box, possibly cropping parts of the image to maintain its aspect ratio.
- background-repeat: no-repeat: Ensures the image doesn’t repeat.
- background-position: center: Centers the image within the box.
- background-color: Provides a fallback color in case the image fails to load.
The Importance of the Box Model in Layout Design
Understanding the box model is essential for creating well-structured and visually appealing layouts. It helps you manage the spacing between elements, control the size of content areas, and create complex layouts using just a few lines of CSS.
When working with CSS, it’s crucial to remember that the width and height properties only define the size of the content area, not including padding, borders, or margins. This can sometimes lead to confusion, especially when trying to precisely size elements. To account for padding and borders in the element’s total width and height, you can use the box-sizing property:
With box-sizing: border-box, the width and height properties include padding and border, making it easier to size elements precisely.
By mastering the box model, you can gain full control over your web layouts, leading to more flexible and maintainable designs.
Visibility
In web development, there are several techniques to hide or show elements on a webpage. Understanding the differences between these methods is crucial for controlling the layout and behavior of elements in your design.
display Property
The display property controls the rendering of an element on the page.
-
display: none;: This completely removes the element from the document’s layout. The element is not rendered, and it does not occupy any space on the page. It is as if the element doesn’t exist in the DOM. This method is commonly used when you need to conditionally include or exclude elements without affecting the layout of other elements.In this example, the
<div>with the IDdisplaywill not be rendered on the page, and any content within it will be hidden without affecting the layout of surrounding elements.
visibility Property
The visibility property controls whether an element is visible or hidden, but unlike display: none;, it does not remove the element from the document flow.
-
visibility: hidden;: This hides the element, but the element still occupies space in the layout. The element is simply invisible, but the space it would normally take up remains, maintaining the layout as if the element were still visible.In this example, the
<div>with the IDdisplaywill be hidden from view, but the space it occupies will remain, ensuring that the layout of other elements is not disrupted.
Key Differences
-
display: none;: The element is completely removed from the layout and does not affect the positioning or layout of other elements. This is useful for situations where you want to dynamically include or exclude content without leaving empty space. -
visibility: hidden;: The element is hidden but still takes up space in the layout. This is useful when you want to temporarily hide content without shifting other elements around, preserving the overall layout structure.
Example Usage
div#display {
/* Uncomment one of the following to see the effect */
/* Completely removes the element from the layout */
/* display: none; */
/* Hides the element but keeps the space it occupies */
visibility: hidden;
}
When to Use Each
-
Use
display: none;when you need to hide an element and do not want it to occupy any space on the page. This is particularly useful for toggling elements on and off in response to user interactions, such as in dropdown menus, modals, or conditional rendering based on user input. -
Use
visibility: hidden;when you want to hide an element but maintain the layout as if the element were still visible. This is often used in animations, where an element might fade in or out without affecting the surrounding layout, or when you want to toggle visibility without reflowing the page content.
By understanding and appropriately using these properties, you can create dynamic and responsive web layouts that behave exactly as intended, whether you’re showing or hiding elements.
Positioning
Positioning in CSS is a powerful tool that allows you to control the layout of elements on a webpage. By understanding how different positioning methods work, you can create complex and dynamic layouts with ease.
The position Property
The position property determines how an element is positioned within the document flow. There are five main values:
-
static: This is the default positioning method. Elements are positioned according to the normal document flow, without any special positioning applied.top,bottom,left,right, andz-indexproperties do not apply to statically positioned elements. -
relative: The element is positioned relative to its original position in the document flow. You can use thetop,bottom,left, andrightproperties to nudge the element from its default location.In this example, the element is moved 20px down and 20px to the right from its original position.
-
absolute: The element is positioned relative to its nearest positioned ancestor (an ancestor with apositionvalue other thanstatic). If no such ancestor exists, it is positioned relative to the initial containing block (usually the<html>element). The element is removed from the normal document flow, meaning it doesn’t affect the position of subsequent elements.Here, the element will be positioned 50px from the top and 30px from the right of its nearest positioned ancestor.
-
fixed: The element is positioned relative to the viewport, meaning it stays in the same place even when the page is scrolled. Likeabsolute, it is removed from the normal document flow.This element will always appear 10px from the bottom and 10px from the right of the viewport, even when the page is scrolled.
-
sticky: The element toggles betweenrelativeandfixedpositioning depending on the user’s scroll position. It’s positioned relative until it reaches a defined scroll position, then it “sticks” in place likefixed.This element will stick to the top of the page when you scroll past it.
Placement Properties
Once an element’s position is set, you can use the following properties to adjust its placement:
top/bottom: Specifies the vertical position of the element.left/right: Specifies the horizontal position of the element.z-index: Controls the stack order of elements. Higherz-indexvalues are rendered in front of lower values.
Here’s an example of a box being positioned relatively:
In this example, the box is moved 20px to the right and 20px down from its original position and is placed behind other elements due to the negative z-index.
Float
The float property is another positioning technique that allows elements to float to the left or right of their container, with surrounding content flowing around them. This was historically used to create layouts before more modern methods like Flexbox and Grid became common.
<!-- Float Example -->
<section>
<div class="left">1</div>
<div class="right">2</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique sapien ac erat tincidunt, sit amet dignissim lectus vulputate. Donec id iaculis velit. Aliquam vel malesuada erat.
Praesent non magna ac massa aliquet tincidunt vel in massa. Phasellus feugiat est vel leo finibus congue.
</p>
</section>
With the following CSS:
section {
border: 1px solid blue;
}
section div {
margin: 5px;
width: 50px;
height: 50px;
}
section .left {
float: left;
background: pink;
}
section .right {
float: right;
background: cyan;
}
In this example:
- The
.leftdiv floats to the left, and the.rightdiv floats to the right. - The paragraph text wraps around these floated elements.
Floats are useful for simple image wraps or basic layout techniques, but they can be tricky to work with for complex designs, especially when dealing with multiple elements and clearing floats. For modern layouts, it’s often better to use Flexbox or Grid.
Example: Floating an Image
<div id="container">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique sapien ac erat tincidunt, sit amet dignissim lectus vulputate. Donec id iaculis velit. Aliquam vel malesuada erat.
Praesent non magna ac massa aliquet tincidunt vel in massa. Phasellus feugiat est vel leo finibus congue.
</p>
<p>
<img src="https://picsum.photos/200" alt="Random" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae
scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu,
lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet
sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam
velit.
</p>
</div>
With the following CSS:
In this example:
- The image floats to the right of its container, with the surrounding text wrapping around it.
- A left margin of 10px is added to create some space between the image and the text.
This technique is particularly useful for embedding images within text-heavy content, where you want the text to flow naturally around the image.
Modern Alternatives: Flexbox and Grid
While position and float are still important to know, modern web design often relies on Flexbox and Grid for more robust, flexible, and responsive layouts. These newer techniques offer more control over element alignment, distribution, and space management, making them the preferred choice for most new projects.
Flexbox
Flexbox is a powerful layout tool in CSS that allows you to design complex layouts in a more efficient and predictable way. Here’s a brief introduction to Flexbox with some examples:
Basics of Flexbox
Flexbox, or Flexible Box Layout, is a layout model system designed to help you structure your HTML elements in a way that they can adapt to different screen sizes and viewports.
To use Flexbox, you first need to define a container as a flex container using display: flex;. This makes all its direct children (or “flex items”) flexible and allows them to adapt to the container’s size.
Example 1: Centering Content
Flexbox makes it incredibly easy to center content both vertically and horizontally.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flexbox Centering</title>
<style>
.center-container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 200px;
border: 1px solid black; /* For visualization */
}
</style>
</head>
<body>
<div class="center-container">
<p>Centered content</p>
</div>
</body>
</html>
Example 2: Responsive Layout with Flexbox
Flexbox is also great for creating responsive layouts where elements can grow and shrink based on screen size.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Flexbox Layout</title>
<style>
.flex-container {
display: flex;
gap: 10px; /* Spacing between elements */
}
.flex-item {
flex: 1; /* Elements grow and fill available space */
border: 1px solid black; /* For visualization */
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">Element 1</div>
<div class="flex-item">Element 2</div>
<div class="flex-item">Element 3</div>
</div>
</body>
</html>
In this example, we have three elements that evenly share the available space in the container. If the screen size changes, the elements will adapt and fill the available space.
Flexbox has many other properties and possibilities, but these two examples showcase some of the most common uses. By experimenting with Flexbox, you can discover how powerful and flexible it truly is for designing modern web layouts. For example, try https://flexbox.help/ or this example of a simple flexbox:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Flex</title>
<style>
.box div {
width: 50px;
height: 50px;
margin: 10px;
background-color: antiquewhite;
}
.box {
width: 300px;
height: 300px;
display: flex;
flex-direction: row;
/* flex-direction: row-reverse; */
/* flex-direction: column; */
/* flex-direction: column-reverse; */
background-color: red;
}
</style>
</head>
<body>
<div class="box">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
</body>
</html>
Try changing the flex-direction property.
Another example is the classic holy grail of design - check https://codepen.io/takeradi/pen/MyYqKX or this HTML and CSS code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Holy Grale</title>
<style>
body {
display: flex;
flex-direction: column;
min-height: 100px;
text-align: center;
}
body .header {
width: 100%;
height: 60px;
background: pink;
}
body .holygrail-body {
flex: 1 0 auto;
display: flex;
}
body .holygrail-body .content {
flex: 1 0 auto;
background: lightgreen;
}
body .holygrail-body .nav {
width: 100px;
list-style: none;
text-align: left;
order: -1;
background: yellow;
margin: 0;
}
body .holygrail-body .aside {
width: 100px;
background: orange;
}
body .footer {
width: 100%;
height: 60px;
background: cyan;
}
</style>
</head>
<body>
<header class="header">Header</header>
<div class="holygrail-body">
<div class="content">Content</div>
<ul class="nav">
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
</ul>
<div class="aside">Aside</div>
</div>
<footer class="footer">Footer</footer>
</body>
</html>
This example showcases a classic layout design using Flexbox, including a header, content area, navigation, aside, and footer. You can experiment with this code to see how Flexbox allows you to create flexible and responsive layouts.
Responsive design involves creating a design that adapts to the current state of the browser, such as the viewport size, rendering for browser or print, or specific resolutions.
Grid
CSS Grid is a two-dimensional layout system in CSS that lets you arrange elements into rows and columns at the same time. This makes it ideal for building entire web page layouts or complex UI structures. While Flexbox focuses on one dimension (either horizontal or vertical), Grid handles both dimensions simultaneously, giving you much greater control over spacing, alignment, and distribution.
Basics of Grid
To use Grid, you define a container with display: grid;. This turns the container into a grid container, and its direct children become grid items.
The power of Grid comes from its ability to define:
- Columns – vertical divisions of the layout.
- Rows – horizontal divisions of the layout.
- Gaps – spacing between rows and columns (
row-gap,column-gap, orgap). - Areas – named regions of the grid that allow you to describe your layout in a very human-readable way.
Unlike older layout methods (tables, floats, inline-block), Grid was designed specifically for layouts and makes responsive design much simpler.
Example 1: Simple Grid Layout
In this example, we create a grid with three columns and two rows. Each item automatically flows into the next available cell.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Grid</title>
<style>
.grid-container {
display: grid;
grid-template-columns: 100px 1fr 2fr; /* three columns */
grid-template-rows: auto auto; /* two rows */
gap: 10px; /* spacing between cells */
border: 1px solid black;
padding: 10px;
}
.grid-item {
border: 1px solid gray;
background: lightblue;
text-align: center;
padding: 10px;
}
</style>
</head>
<body>
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
</div>
</body>
</html>
Here’s what happens:
- The first column has a fixed width of
100px. - The second column takes up one fraction (
1fr) of the remaining space. - The third column takes up twice as much (
2fr). - Rows are automatically sized (
auto) based on their content.
This makes it easy to combine fixed and flexible sizing in one layout.
Example 2: Grid Areas
Grid lets you name parts of your layout and then place elements directly into those areas. This makes your CSS very descriptive and easy to maintain.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grid Areas</title>
<style>
.grid-container {
display: grid;
grid-template-areas:
"header header header"
"sidebar main ads"
"footer footer footer";
grid-template-columns: 1fr 3fr 1fr;
grid-template-rows: auto 1fr auto;
gap: 5px;
height: 300px;
}
.grid-container > div {
padding: 10px;
color: white;
}
.header { grid-area: header; background: pink; }
.sidebar { grid-area: sidebar; background: orange; }
.main { grid-area: main; background: green; }
.ads { grid-area: ads; background: purple; }
.footer { grid-area: footer; background: cyan; }
</style>
</head>
<body>
<div class="grid-container">
<div class="header">Header</div>
<div class="sidebar">Sidebar</div>
<div class="main">Main</div>
<div class="ads">Ads</div>
<div class="footer">Footer</div>
</div>
</body>
</html>
How it works:
grid-template-areasdefines the overall layout in text form.- Each grid item is assigned to a named area using
grid-area. - The layout becomes easy to read (and almost looks like ASCII art).
This approach is often used to build the so-called “Holy Grail Layout” (header, footer, sidebar, and main content).
Example 3: Responsive Grids with repeat() and fr
Grid provides special units like fr (fractional unit) that let you create flexible, responsive layouts without calculating percentages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Grid</title>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
gap: 10px;
}
.grid-item {
border: 1px solid black;
padding: 20px;
text-align: center;
background: lightcoral;
}
</style>
</head>
<body>
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
</div>
</body>
</html>
repeat(3, 1fr)creates three columns of equal size.- As the viewport changes, the columns resize automatically.
- By changing the number inside
repeat(), you can quickly create 2, 4, or more columns.
This makes it easy to design responsive galleries, dashboards, or card layouts.
Grid vs Flexbox
Both Flexbox and Grid are modern layout tools, but they serve different purposes:
- Flexbox is best for one-dimensional layouts (e.g. navbars, button groups).
- Grid is best for two-dimensional layouts (entire pages, complex components).
In practice, you often use them together: Grid for the large structure, Flexbox for the smaller details inside components.
Responsive Design with Media Types, Media Queries, and CSS Grid
Responsive design is crucial for creating websites that work well on a variety of devices and screen sizes. This is achieved through a combination of media types, media queries, and modern layout techniques like CSS Grid.
Media Types
Originally, responsive design started with the use of media types, which allowed developers to apply different styles depending on the target medium, such as screen or print. This was the foundation of adapting a website’s appearance for various devices.
Example: Media Type for Print
In the example below, the text color is red by default but switches to black when printed:
Here, the @media print rule targets the print media type, applying specific styles when the content is printed.
Media Queries
Media queries are a more advanced and flexible way to create responsive designs. They allow you to apply styles based on specific conditions, such as screen size, resolution, or device orientation. This enables you to adapt your design to different devices dynamically.
Example: Responsive Text Color with Media Queries
<div id="qtype">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestias fuga ad maiores nesciunt
voluptatibus facere reiciendis. Beatae repellendus, sint provident iusto distinctio cumque
voluptatibus deleniti cupiditate eveniet nobis iure eos!
</div>
div#qtype {
color: black;
}
@media only screen and (min-width: 400px) {
div#qtype {
color: red;
}
}
@media only screen and (min-width: 800px) {
div#qtype {
color: blue;
}
}
@media only screen and (min-width: 1000px) {
div#qtype {
color: green;
}
}
In this example, the text color changes based on the screen width: - On screens wider than 400px, the text turns red. - At 800px, it changes to blue. - At 1000px, it turns green.
This technique allows your website to adapt fluidly to different screen sizes, improving user experience on a variety of devices.
Responsive Layouts with CSS Grid
CSS Grid is a powerful, two-dimensional layout system that provides more control over page structure than traditional methods like float or position. It’s especially useful for creating responsive layouts that adapt to different screen sizes.
Example: Basic Grid Layout
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
</div>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Three columns */
grid-template-rows: 100px 100px; /* Two rows */
gap: 10px; /* Gap between grid items */
}
.grid-item {
background-color: lightblue;
border: 1px solid black;
text-align: center;
padding: 20px;
}
This example creates a grid with three columns and two rows, automatically arranging six items within the grid. The grid-template-columns and grid-template-rows properties define the size and number of columns and rows, while gap controls the spacing between items.
Example: Responsive Grid Layout
You can make your grid layout responsive by using media queries to adjust the number of columns based on screen size:
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
</div>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Three columns */
gap: 10px;
}
.grid-item {
background-color: lightblue;
border: 1px solid black;
text-align: center;
padding: 20px;
}
/* Responsive layout for smaller screens */
@media (max-width: 600px) {
.grid-container {
grid-template-columns: 1fr; /* One column */
}
}
In this example, the grid adapts to different screen sizes: - On screens wider than 600px, the layout shows three columns. - On smaller screens, it switches to a single-column layout for easier readability.
Bringing It All Together
Responsive design techniques, such as media types, media queries, and CSS Grid, allow you to create flexible and adaptable web layouts that provide a great user experience across a wide range of devices. By combining these tools, you can ensure that your website looks and functions well, whether viewed on a small mobile screen or a large desktop monitor.
For further learning and examples, check out resources like the University of Vermont’s website for excellent examples of responsive design, or explore more about CSS Grid at https://grids.help/.
Animations
Animations are an essential part of modern web design, allowing you to create dynamic and engaging user interfaces. CSS animations can enhance user experience by providing smooth transitions and interactive elements without relying on JavaScript. The foundation of CSS animations lies in transforms, transitions, and keyframe animations.
Transforms
Transforms allow you to manipulate elements by scaling, rotating, translating (moving), and skewing them. These operations can change the shape, size, and position of elements on the page.
Basic Transform Functions
scale: Resizes an element. You can scale elements up or down.
rotate: Rotates an element around its center.
translate: Moves an element from its original position. It takesxandyvalues.
skew: Skews (distorts) an element along thexoryaxis.
transform: skew(20deg, 10deg); /* Skews the element 20 degrees along the X-axis and 10 degrees along the Y-axis */
Example: Rotating an Element
<div id="transf">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestias fuga ad maiores nesciunt
voluptatibus facere reiciendis. Beatae repellendus, sint provident iusto distinctio cumque
voluptatibus deleniti cupiditate eveniet nobis iure eos!
</div>
div#transf {
width: 400px;
transform: rotate(-5deg); /* Rotates the element 5 degrees counterclockwise */
}
In this example, the text inside the div#transf element is rotated slightly to create a subtle visual effect.
Transitions
Transitions allow you to change property values smoothly (over a given duration) when an element changes state, such as when it is hovered over, focused, or clicked. Transitions work in conjunction with transforms to create dynamic effects.
Example: Changing Background Color on Hover
<div id="trans">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestias fuga ad maiores nesciunt
voluptatibus facere reiciendis. Beatae repellendus, sint provident iusto distinctio cumque
voluptatibus deleniti cupiditate eveniet nobis iure eos!
</div>
div#trans {
width: 400px;
background-color: yellow;
transition-duration: 2s; /* Smooth transition over 2 seconds */
}
div#trans:hover {
background-color: red; /* Changes the background color to red on hover */
}
In this example, when you hover over the div#trans element, the background color gradually changes from yellow to red over a period of 2 seconds.
Keyframe Animations
Keyframe animations provide a way to create complex animations by defining multiple steps (keyframes) that an element will go through over a period of time. Each keyframe specifies a particular style that should be applied at a specific point in the animation sequence.
Example: Moving and Changing Colors with Keyframes
div#kf {
width: 100px;
height: 100px;
position: relative;
animation: boxani 5s; /* Apply the animation 'boxani' over 5 seconds */
}
@keyframes boxani {
0% {
background: green;
left: 0px;
top: 0px;
}
25% {
background: blue;
left: 150px;
top: 0px;
}
50% {
background: red;
left: 150px;
top: 150px;
}
75% {
background: yellow;
left: 0px;
top: 150px;
}
100% {
background: green;
left: 0px;
top: 0px;
}
}
In this example:
- The element starts at the top-left corner of its container (0% keyframe).
- It moves right and changes color at the 25% keyframe.
- It continues to move down and change color at the 50% keyframe.
- Then it moves left and changes color again at the 75% keyframe.
- Finally, it returns to its original position and color at the 100% keyframe.
The animation property defines the animation name (boxani), its duration (5 seconds), and any other optional parameters such as delay, iteration count, and timing function.
Putting It All Together
CSS animations offer a powerful way to enhance your web design with dynamic, visually appealing effects. By combining transforms, transitions, and keyframe animations, you can create everything from simple hover effects to complex, multi-step animations.
Here’s a quick summary of when to use each: - Transforms: For scaling, rotating, moving, or skewing elements. - Transitions: For smooth changes in property values triggered by user interactions. - Keyframe Animations: For complex, multi-step animations that require precise control over an element’s behavior over time.
These tools allow you to create interactive and engaging web experiences that can captivate users and enhance the overall usability of your site.
CSS libraries
There are several libraries with predefined CSS animations. You can, for example, take a look at the following:
Functions
Modern CSS provides a variety of powerful functions that enhance styling capabilities. These functions can make your CSS more dynamic, flexible, and maintainable. However, as with any advanced features, it’s a good practice to check browser compatibility on Can I use before using them in production.
CSS Variables (Custom Properties)
CSS Variables, also known as custom properties, allow you to define reusable values in your stylesheets. They enable you to maintain consistency across your designs and make global updates much easier.
Defining and Using Variables
Variables are defined within a CSS selector, most commonly :root, which represents the highest-level parent in the document (typically the <html> element). Using :root makes the variables globally accessible throughout the stylesheet.
--main-bg-color,--main-txt-color, and--main-paddingare custom properties (variables) that store specific values.
These variables can then be used elsewhere in your CSS using the var() function:
h1 {
color: var(--main-txt-color);
}
div {
color: var(--main-txt-color);
background-color: var(--main-bg-color);
padding: var(--main-padding);
}
In this example:
- The h1 element’s text color is set using the --main-txt-color variable.
- The div element’s text color, background color, and padding are set using the corresponding variables.
Using variables can significantly simplify managing design tokens like colors, spacing, and typography across large projects. If you need to change the primary color throughout the site, you only need to update the variable value.
Calculations
CSS allows you to perform calculations directly in your styles using the calc() function. This can be particularly useful for creating responsive designs, where element sizes need to be flexible and adapt to different screen sizes.
Example: Responsive Banner
Here’s an example of how to use calc() to create a responsive banner that adapts to the width of the viewport:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Banner</title>
<style>
.banner {
position: absolute;
left: 90px;
width: calc(100% - 180px);
border: solid black 1px;
background-color: thistle;
text-align: center;
}
</style>
</head>
<body>
<div class="banner">Banner!</div>
</body>
</html>
In this example:
- The banner is positioned 90px from the left edge of the viewport.
- The width of the banner is calculated as 100% - 180px, ensuring that it spans the full width of the viewport minus a 90px margin on each side.
The calc() function allows you to mix units (like percentages and pixels), making it a powerful tool for creating layouts that need to be both flexible and precise.
Attribute Functions
The attr() function in CSS allows you to access and display the value of an HTML attribute directly in your styles. This can be particularly useful for dynamically generating content based on element attributes.
Example: Displaying an href Attribute
Here’s an example that demonstrates how to use the attr() function to display the href attribute of a link as part of its content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Attr Demo</title>
<style>
a::after {
content: "[" attr(href) "]";
}
</style>
</head>
<body>
<a href="https://www.google.com">Google</a>
</body>
</html>
In this example:
- The attr(href) function accesses the href attribute of the <a> element.
- The ::after pseudo-element appends the href value within square brackets to the content of the link.
This results in the link text being displayed as Google [https://www.google.com], which can be useful for showing the URL of a link, especially in print stylesheets or for accessibility purposes.
Color Functions
CSS also offers functions that allow you to manipulate colors directly within your styles. Some of the most common color functions include:
rgba(): Defines colors with Red, Green, Blue, and Alpha (opacity) components.
hsla(): Defines colors using Hue, Saturation, Lightness, and Alpha components.
hsl()andrgb(): Similar tohsla()andrgba()but without the alpha component.
These functions enable more granular control over colors, particularly when you need to adjust transparency or create colors programmatically.
Gradients
Gradients are another area where CSS functions shine, allowing you to create smooth transitions between colors. CSS supports various types of gradients, including linear and radial gradients.
Example: Linear Gradient
In this example:
- The background of the div will transition smoothly from red on the left to yellow on the right.
Gradients can be customized further by adding more color stops, adjusting the angle or direction, or even combining multiple gradients.
Summary
CSS functions provide a powerful set of tools to make your stylesheets more dynamic and adaptable. From defining and reusing variables to performing calculations and manipulating colors, these functions allow you to write more maintainable and responsive CSS.
As with all advanced features, always check browser compatibility before relying on these functions in production, especially for critical aspects of your design. The website Can I use is an excellent resource for checking support across different browsers and devices.