Your cart is currently empty!
Category: InfoComTech
Information technology has changed business processes, information management, information dissemination, and commerce in recent times. Virtually everything we do has a link with technology.
Learn coding and programming the easy way. The knowledge you need to unmask your creativity and creative ability.
Using Transform Property and CSS3 Animations in Web Design
In this last tutorial in CSS3, we will discuss CSS3 animations and the transform property. In our previous tutorial, we looked at fonts in web design. If you have not checked it out, you can visit here.
The transform property and CSS3 animations are used to add life to HTML elements during user interaction. It allows us to smoothly transition elements from one style to another without the use of JavaScript.
CSS3 animations have two major components: the animation property and the @keyframes at-rule.
@Keyframe at-rule
@keyframes is used to define each stage of the css3 animations process. Before applying the animation property, we should first define what should happen at each point of the animation. That is, from the beginning (0%) of the animation to the end (100%) of the animation.
This definition is usually created using the @keyframes rule. @keyframes could be seen as a transition timeline or sequence. It is a transition order that specifies the state of an element from the start of the animation to the end.
The simplest css3 animation has only two @keyframes at-rule: the start and end.
For example:
@keyframes myanim{ 0%{background-color: red;} 100%{background-color: green} } #sti:hover{ animation-name: myanim; animation-duration: 3s; }
When defining complex animations, you can have multiple @keyframes at-rule, from the start to the end.
For example:
@keyframes myanim{ 0%{background-color: red;} 25%{background-color: orange;} 50%{background-color: green;} 75%{background-color: blue;} 100%{background-color: silver; border-radius: 20px;} } #sti{ animation-name: myanim; animation-duration: 3s; animation-iteration-count:3; }
Creating CSS Animations
Animation property:
The animation property is used to control the @keyframes at-rule. It can be used as a shorthand for the following properties: animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, and animation-play-state.
animation-name: This is used to specify the name of the @keyframes at-rule to be controlled by the animation property. In the above example, this is the myanim.
animation-duration: This property is used to specify the length of time it will take for one cycle of the animation to complete. Its value is specified in seconds (s) or milliseconds (ms).
animation-timing-function: This is used to define the level of acceleration of the animation. It has the following values:
- ease (slow start, then fast and slow end. This is the default),
- linear (same speed from beginning to end),
- ease-in (slow start),
- ease-out (slow end),
- ease-in-out (slow start and end),
- cubic-bezier(x,x,x,x) (a cubic-bezier function that allows you to define your own transition function),
- steps(x) (animation is transitioned in the number of steps specified).
animation-delay: This property is used to delay the animation so that it will not start as soon as it is loaded. Its values are specified in seconds (s) or milliseconds (ms).
animation-iteration-count: This is used to define the number of times a full cycle of animation is repeated. It’s has a default value of 1. Other values include infinite and a unitless number, say, 2, 3, …
animation-direction: This property specifies the direction the animation should play. Its values are:
- normal (default value),
- reverse (plays in reverse order or backwards),
- alternate (plays forward, then reverse), and
- alternate-reverse (plays backward first, then forward).
animation-fill-mode: This is used to set the style values before and after the animation plays. The values include,
- none (default value),
- forwards,
- backwards and
- both.
animation-play-state: This property is used to control the play mode of the animation, whether it should pause or run. It has the following values: running (default) and paused.
We may specify these individual properties or use the animation shorthand property. To use the animation shorthand property, do the following:
div{
animation: animation-name animation-duration animation- timing-function animation-delay animation-iteration-count animation-direction animation-fill-mode animation-play-state;
}
For Example:
#sti{ animation: myanim 3s ease-in infinite alternate; }
The Transform property and CSS 3 Animations
The examples given above are simple. To perform more advance animations in CSS, we need to learn about the transform property.
The transform property is used to alter the original form of an element. To do this, we can scale, rotate, skew, or translate the element. This can be achieved using the 2D or 3D transform property functions.
The transform property can be written as follow:
transform: transform-function();
The transform property function can be any of the following:
- scale()
- skew()
- translate()
- rotate()
- matrix()
Multiple transform property functions can be combined in an element using white spaces. This can be written thus:
transform: transform-function() transform-function();
Let’s define the above transform functions.
- scale(width, height): the scale function is used to alter the size of the element. The default value is 1. Values below 1 scales element down and values above 1 scales element up. Specifying only one value means that both width and height will be proportionately scaled.
- skew(x, y): the skew function is used to distort an element along the horizontal axis(x-value). Or along the vertical axis(y-value), or on both axis.
- translate(x, y): the translate function is used to move an element along the x-axis or the y-axis. It works like a relatively positioned element.
- rotate(deg): the rotate function is used to rotate an element either clockwise or anti-clockwise. Element rotates clockwise between 0 – 360 degrees or anti-clockwise if the rotate value is negative.
- matrix(): the matrix function is used to combine all the 2D transform functions together.
2D Transform function Values
The 2D transform values include the following:
- scale()
- scaleX(): scales only the width of an element. Use unitless values.
- scaleY(): scales only the height of an element.
- skew()
- skewX(): skews element along the x-axis. Use degree values, e.g. 20deg.
- skewY(): distorts element along the y-axis (vertically) only.
- translate()
- translateX(): moves element along the horizontal axis only. Use length values or percentages.
- translateY(): moves element along vertical axis only.
- rotate()
- matrix()
The transform-origin property
The default transform origin is at 50% horizontally and vertically of an element. It is also called the dead center. This can be changed using the transform-origin property.
The transform origin property can take one or two values using any of length units, percentages or keywords. Just like the background-size property discussed in the box model.
Length values can be in px, em, etc, percentage values range from 0 to 100%, and keywords value includes the top left, bottom right, etc.
For example:
transform-origin: 25px 45px;
Examples of simple 2D transform is illustrated below.
3D transform values
The difference between the 2D transform and 3D transform values is the perspective property. The perspective is the vanishing point of an element in a 3-dimensional plane.
We can set the perspective property in the parent element or in the individual transform elements. We apply perspective in the parent element when we want to create a group of elements with the same perspective.
The perspective property can take none value or a length value. The higher the value, the further away the perspective appears. The lower the value, the closer the perspective appears on the plane. Use higher values to create low intensity and lower values to create high intensities.
You can also set perspective-origin property just the way transform-origin property is set. It takes the same values as the transform-origin property.
Therefore, in the 3D transform, we need to add another dimension called the Z dimension. The z-axis takes care of the depth of the element in the 3D plane, while the x and y values take care of the horizontal and vertical axis respectively as in the 2D.
The 3D values include:
The skew() function cannot be transformed in 3D, because element cannot be skewed in the z-axis. Other transform functions can be transformed in x, y, and z-axis respectively. Possible values for 3D transform include:
- scale3d(x,y,z)
- scaleX(x)
- scaleY(y)
- scaleZ(z)
- translate(x,y,z)
- translateX(x)
- translateY(y)
- translateZ(z)
- rotate(x,y,z,a): x, y, z = between 0 and 1. a = angle of rotation
- rotateX(xdeg)
- rotateY(ydeg)
- rotateZ(zdeg)
- matrix3d(): combines all the 3D transform values.
transform-style property
The transform-style property is used to maintain the 3D plane of transformed elements. It is usually placed within the transformed elements’ parent container. It has two values: preserve-3d and flat.
The preserve-3d value will permit the child element to transform in their own 3D plane. The flat value will make the transformed child element to be flattened in the 2D plane.
backface-visibility property
This property is used to show or hide the backface of a 3D transformed element. If a transformed element faces away from the 3D plane, then the backface-visibility value can be set to either visible or hidden values. The default value is visible.
Examples:
Conclusion
It is good to learn how to design wonderful websites. But in recent times when access to the internet is mostly done using mobile devices, a responsive website will do better.
One of the criteria to rank on Google is the responsiveness of a website. Google knows and is implementing it in their ranking factor. It is, therefore, necessary to understand and always implement this fact during web design.
We have come to the end of this 3-course series on Cascading stylesheets. The aim is to help you style your websites at every stage of progress.
We started this course with how to test your site for responsiveness. You can use all the methods or use the online method. This method allows you to test on different devices at the same time.
We then jumped to fonts. We looked on how to work with generic, custom and web fonts. We then did justice to CSS animations, after which we concluded with responsive websites.
I believe your following to this point is not a disappointment. I will want to attend to your questions. Post them in the comment for everyone to see and interact. I will also want to see your first website.
I will advise you to visit:
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference
for complete CSS properties reference.
Fonts in Web Design: Working with Generic and Web Fonts Service
Fonts are used to define the nature of texts. They define the text’s character look, size, weight, and style. Fonts in web design are used to define the nature of texts on a web page.
There are thousands of fonts available, but all these fonts are not installed in users’ systems. In web design, it is good practice to define the fonts you are expecting your texts to display in users’ browsers.
When defining fonts in web design, we can combine generic, custom and web fonts.
Fonts in Web Design
Generic fonts
Some fonts are guaranteed to be available across all platforms and systems. These kinds of fonts are called web-safe fonts. When defining fonts in web design, especially, a font-family, it is advisable to declare any kind of font. But in the end, always declare web-safe fonts, as a fallback.
Some web-safe fonts include Arial, Times New Roman, Helvetica, Georgia, Impact, Verdana, Courier New, Trebuchet MS, Comic Sans MS, etc. Most of these fonts belong to the generic font’s family as discussed below.
Generic fonts include serif, sans-serif, monospace, cursive and fantasy. Let’s check the features of each of them briefly.
Serif fonts define fonts with small lines at the end of each character. They include the following font-family: ‘times new roman’, times, Georgia, serif, bookman, etc.
Sans-serif are fonts without serif. They include the following font-family: Arial, sans-serif, ‘trebuchet ms’, Verdana, Helvetica, Tahoma, etc.
Monospace is fonts with fixed width. They are fonts in the following font-family: ‘courier new’, ‘Lucida console’, monospace, Consolas, ‘Ocr a extended’, etc.
Cursive fonts define fonts that look like handwriting. It usually has connecting strokes. It includes the following font-family: cursive, comic sans, brush script mt, Bradley hand, etc.
Fantasy fonts are fonts that have decoration, especially used for titles. The font-family include impact, fantasy, luminary, etc. Some of the fantasy fonts may not be used across browsers.
Defining fonts in web design
When defining fonts in web design, the following properties can be individually specified. We can also use the Font shorthand property to specify them as follow:
font: font-style font-variant font-weight font-stretch font-size/line-height font-family
E.g.
p{ font: italic small-caps bolder expanded 1.5em/1.5 cursive, 'trebuchet ms' Georgia; }
The shorthand method requires only the font-size and font-family, while a slash (/) is used in between font-size and line-height
Let’s look at the individual properties.
font-style property: This property is used to specify the text stylishness. It has the following values: normal, italic, and oblique.
font-variant property: This is used to specify normal text or small caps text. Its values are: normal and small-caps.
font-weight property: This is used to specify the boldness of text content. It has the following values: normal, bold, bolder, lighter, 100 – 900.
font-stretch property: Is used to expand or compress text content. It has the following values: normal, condense, semi-condensed, extra-condensed, ultra-condensed, expanded, semi-expanded, extra-expanded, ultra-expanded.
font-size: Used to specify the extent or dimension of text content. It has the following values pixels, ems, rems, VW (viewport width), percentages, etc.
line-height property: used to set the height of each line of text. The values usually take a unitless value or unit of length values.
font-family property: used to specify the family of texts. Values include ‘trebuchet ms’, Verdana, Arial, ‘times new roman’, serif, etc.
@font-face property
We use the @font-face rule to include custom fonts or web fonts to web pages. A non-generic font is usually defined using @font-face. If such a font is not in the users’ computer, it will be automatically downloaded to the user when needed.
These days, there are thousands of fonts to choose from by any web designer. You are not limited to the generic fonts. As a web designer, you have the option of using any font of your choice. All you need do is to correctly include the font in your CSS at ruleset.
Before proceeding, let us take note of the following:
- Some fonts are free while others are commercially provided. To use any font on your website you must have the appropriate licensing.
- Some font formats are not supported across browsers. Different browsers support different font formats. For example:
- Embedded Open Type (.eot) fonts are supported by Internet Explorer only.
- True Type Font and Open Type Font (.ttf/.otf) are supported by major browsers such as Internet Explorer, Chrome, Firefox, Opera and Safari.
- Web Open Font Format (.woff) is also supported across browsers: Internet Explorer, Chrome, Firefox, Opera and Safari. However, WOFF version 2 (.woff2) is not supported by IE and Safari.
- Scalable Vector Graphic (.svg) fonts are supported by Chrome, Opera, and Safari.
Hence, before you choose a font, be careful to know the format, and ensure that it can be supported by most browsers.
Using custom fonts in web design
- To use custom fonts in web design, we need to first download the font from free fonts distributors or commercial font distributors.
NOTE: Even if we are using the free fonts, you must understand that to use the font for commercial purposes, you need to obtain a commercial license. Free fonts are mostly for personal use.
Some free fonts distributors include:
In this tutorial, we will download and use Heavenly Script from Befonts. You can actually use any font of your choice. Just follow the procedure.
- Visit Befonts website @ https://befonts.com/
- search for Heavenly Script, or any font of your choice
- select the font when displayed,
- scroll down and click download.
- After downloading fonts from any of the above font distributors, unzip the downloaded fonts. Then save it in your website files folder.
Make sure the font’s file is placed in the same location as your CSS file. For example, the downloaded font has been unzipped and placed in the same location as my website files.
- You might decide to rename the font’s file name for easy access. But remember to take note of the file extension name, that is, the font format: .ttf, .otf. .woff, etc.
For example, the downloaded font is an OpenType Font (.otf). I just changed the name to ExFont.otf.
- Open your CSS file and enter the following codes in the first line:
@font-face{ font-family: ExFont; src: URL("ExFont.otf"); }
- If you want to include more than one font-family, repeat No. 4 as many times as the number of fonts you want to include.
For example,
@font-face{ font-family: ExFont; src: url("ExFont.otf"); } @font-face{ font-family: Cassandra; src: url("Cassandra.ttf"); } @font-face{ font-family: "Lovely Home"; src: URL("Lovely Home.ttf"); }
- If you have more than one type of the same font’s format, include them in your URL function, separated by a comma. Also, include each file format.
For example,
@font-face{ font-family: ExFont; src: url("ExFont.otf") format(“opentype”), url(“ExFont.ttf”) format(“truetype”), url(“ExFont.woff”) format(“woff”), url(“ExFont.woff2”) format(“woff2”); }
- Apart from the font-family and src properties, you may also specify font-weight and font-style properties in the @font-face at-rule.
For example,
@font-face{ font-family: ExFont; src: URL("ExFont.otf"); font-weight: bold; font-style: italic; }
- Finally, include the defined font-family in any element of your HTML, with a generic font at the end. For example,
p{ font-family: ExFont, sans-serif; }
Using Web fonts in Web Design
Custom font requires that you will download the font first, and then upload the same to your server. Your users will also be required to download the font when they access your website.
Instead of doing this, an easier and better option is to use an online font service. The advantage of using an online font service is that they store and serve the fonts from their servers. This will help you save bandwidth.
Some of the online font services are:
Web Font Service
Requirement
requires creative cloud subscription
requires licensing
requires cloud or self-hosted subscriptions
completely free, but uses JavaScript instead of CSS.
completely free
We shall illustrate with Adobe Edge Web Fonts and google fonts.
Adobe Edge Web Fonts
Using Adobe Edge Fonts is simple and straight forward:
- Go to http://www.edgefonts.com/index
- Click on Get Started to display a list of available fonts as shown below:
- Point at your desired font and click on +select this font.
- It will display the JavaScript source file and CSS declaration as shown below:
- Copy the Javascript source file and add it to the <head> section of your HTML file, and copy the CSS font-family declaration and paste it in your CSS file.
For Example:
<!Doctype html> <html> <head> <script src="//use.edgefonts.net/aguafina-script.js"></script> </head> <body> <p> This is a paragraphy ... </p> </body>
CSS File Code:
p{ font-family: aguafina-script, cursive; }
Google Fonts Service
To use the google fonts service, follow the following procedure:
- Visit https://fonts.google.com/
- In the window that appeared, search for the font of your choice.
- If you locate your desired font, click the (+) button on the right of your chosen font. See the diagram below.
- After you select a font, a dark rectangular box will appear at the bottom of your window displaying 1 Family selected.
Select as many font families as you want.
- When you are done selecting all the fonts you want, click on the dark rectangular box to reveal the CSS information.
- Under Embed Font, copy the CSS external link file information and paste it at the <head> section of your HTML document.
For example, I selected Dancing Script and Righteous fonts. From my selection, I have the following:
<head>
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Righteous" rel="stylesheet">
</head>- Finally, add the font-family property to any HTML element you wish in your CSS code, as was specified.
For example:
section{ font-family: 'Dancing Script', cursive; width: 70%; font-size: 20px; margin: 0 auto; } h1{ background-color: blue; position:sticky; top: 20px; font: italic small-caps bolder expanded 1.5em/1.5 Righteous; } p{ font-family: 'Dancing Script', cursive; font-stretch: expanded; }
Your website should by now look differently.
This is where we will end today’s tutorial. Remember to visit our tutorials on Responsive web design and how to use the @media rules to create a responsive website. Video courses are also available. You can start here.
Next week, we shall complete our tutorials on CSS with the transform property and CSS Animations. Hoping to get your feedback.
Media Query Breakpoint in Responsive Web Design
In our previous post, we introduced @media rule. In this post, we are going to give detail of media query breakpoint and responsive web design.
@media at-rule
To create a responsive website, we use media query. This enables us to create breakpoints based on our layout to suit different device sizes. As explained above, 3 different device sizes may be targeted, namely phones, tablets, and desktops.
Media queries are logical expressions used to create different style rules. Using the @media and @import properties we can create different styles for different devices. These styles activate when the conditions are true.
When using media query, we can target 3 different things:
- media type only,
- media features only, or
- media type and media features.
To use the media query (@media property), the syntax is as follow for each:
- To target specific media types: @media media-type {css blocks}
For example:
@media screen{ section{ color: #00ff00; font-size: 16px } }
- To target specific media features: @media (media-features) {css blocks}
For example:
@media (max-width: 768px){ section{ color: #ff0c32; font-size: 14px } }
- To target both media types and media features: @media media-type logical-expression (media-features) {css blocks
For example:
@media screen, print and (min-width: 768px){ section{ color: #00ff63; font-size: 14px } }
Media types
These are categories of devices that should be targeted. Media type could be any of the following:
all – Used to target all devices
print – This media type is used to target HTML pages viewed in print preview mode
screen – Is used to target different sizes of screen
speech – Is used to target speech synthesizers
Media features
These refer to the characteristics or attributes of the devices used by the users to access the web page. They are always enclosed in parentheses. The following are some of the media features that can be included in the @media rule-set.
aspect-ratio – is used to specify the width/height aspect ratio of the device’s viewport. Its value is in units of length. It can also take a min/ max prefix.
width – is used to target the width of the device’s viewport. Its value is in units of length. It can also take a min/ max prefix.
height – is used to target the height of the device’s viewport. Its value is in units of length. It can also take a min/ max prefix.
orientation – is used to target the orientation of the device’s viewport. Its value is either portrait or landscape.
resolution – is used to target the pixel density of the user’s output device. Its value is in dots per inch (dpi) or dots per pixel (dppx).
scan – used to target the scanning process of an output device.
grid – used to target a grid or bitmap screen device. Its value is either 1 for grid devices or 0 for other devices.
color – used to target the bits per color component of the output device. The value is an integer.
color-index – used to target the number of entries in the user’s output device’s color lookup table. Its value is an integer.
color-gamut – used to target the range of colors supported in the user’s output device.
monochrome – used to target the number of bits per pixel in the user’s output device’s monochrome frame buffer. Its value is an integer. It is 0 if the device is not monochrome.
display-mode – used to target the display mode specified in the web app manifest.
pointer – used to identify whether the primary input mechanism is a pointing device.
hover – used to determine if the primary input mechanism allows users to hover over an element.
There are many more features, including any-pointer, any-hover, inverted-colors, update, overflow-inline, overflow-block, light-level, prefers-reduced-transparency, prefers-contrast, scripting, and prefers-color-scheme.
Logical operators
The logical operators can be used to combine media type and media features together. They can also be used to create complex @media queries. Some of the logical operators used include:
and operator – This operator is used to join media type and media features together. It also joins multiple media features together. The implication of an and operator is that all media categories concerned must be TRUE for the @media query to execute.
Example
@media screen and (max-width: 768px){ section{ color: #00ff63; font-size: 14px; } div{ display: block; width: 100% } }
This example indicates that the media type is screen while the media feature is the width. Hence, for the query to execute, the user’s device screen size must be less than or equal to 768px. Therefore, the example is used to target smartphones. Thus, the and operator ensures that the media type is screen which size MUST NOT exceed 768px.
not operator – This operator is used to execute the opposite of @media query. The not operator turns a TRUE query to FALSE and a FALSE query to TRUE.
Example
@media screen not (min-width: 768px){ section{ color: #00ff63; font-size: 14px } }
This example implies that the query will evaluate if the min-width of the device’s viewport is NOT 768px. In other words, it applies to devices whose viewport is less than 768px.
only operator – when this operator is used, a media type must be specified. The only operator is used to apply CSS style when an entire query matches.
Example
@media only screen and (max-width: 768px){ article{ width: 90%; float: none; background-color: gray; } }
This query will execute only if the entire query matches. That is, target device screen must be less than 768px.
“,” (comma) operator – This operator works like an or operator. It is used to combine media types or combine separate queries as one. When the “,” operator is used, any of the queries that are true are evaluated.
Example
@media screen and (min-height: 480px), screen and (orientation: landscape){ article{ width: 90%; float: none; background-color: gray; } }
This means that either of the two queries can be executed if true. If the media type is screen and has a minimum height of 480px, the style will be applied. Similarly, if the media type is screen and has an orientation of landscape. The query will also be executed.
Media Query Breakpoint and Responsive Web Design
The HTML and CSS code in the JSFiddle platform below is used to illustrate the normal website that is not responsive. You can copy it to your editor and test to see that it is not responsive.
Let us try to resize the above window to adjust the viewport. The output will look horrible. Text and image will combine together so that you cannot read through the website.
Notice also that the contents overflowed its container as well as overlapped each other.
However, we can add media query breakpoint to make our website responsive. To use media query breakpoint when creating a responsive website, we adjust our code above as shown below. using JSFiddle.
To make our site above responsive, we shall add the following CSS using @media rule as follow:
You can copy the codes to your editor and save the CSS and refresh your browser. Then try resizing the browser window again, you will notice that the site will quickly adjust depending on the viewport.
You can create more complex media query that responds to different viewports. This you can easily do by following the above procedure, but specifying the different viewports.
The important part is to look at the contents you want adjusted when viewport changes. If you are able to know this, you have learnt how to build a responsive website using media query breakpoint.
Using the @import at-rule
We can also create a media query using the @import at-rule set. We use the @import to import a stylesheet that has styles for different media.
It is important to note that when using the @import, we must specify the @import statements at the beginning of the stylesheet.
For example:
@import url(‘styles/media.css’) only screen and (min-width: 500px); /* This will take care of styling for media query breakpoint for devices that has viewport equal to or greater than 500px. That is, it takes care of bigger phones, tablets, and desktops. */
@import url(‘styles/mediamax.css’) screen and (max-width: 500) and (orientation: portrait); /* This will take care of the styling for media query breakpoint for devices that has viewport equal to or less than 500px. That is, it takes care of smaller phones. But the orientation must be portrait. */ html{ margin: 0; padding: 10px; } h1{ font-size: 180% } hgroup div{ height: 200px; background: url("47.jpg"); color: #ffffff; } hgroup h2{ font-size: 38px; } hgroup p{ width: 70%; text-align: center; font-size: 20px; margin: auto; }The imported stylesheet contains the styles that will be applied to the devices based on their specification.
This is where we will stop in creating responsive web design using media query breakpoint. You can learn more by taking the full course here.
Next, we will discuss web fonts.
How to Design a Responsive Web Layout using @Media Rule
We took quite a considerable amount of time to discuss two display property values which include flex and grid. We also learned of their importance in creating flexible and responsive web layouts.
In this course, we will look at how to ensure that our website is suitable for all kinds of devices. We will take time to look at how to design a responsive web layout using @media rule.
In recent times, people connect to the internet with different kinds of devices, including phones, watches, tablets, etc. It is important that you make your website display appropriately in all these devices.
A website is described as responsive if it could automatically adjust its content for optimal viewing in all devices. In this case, the size of the device used to access it would not be a barrier.
Hence, it does not matter what the size of the device used in accessing the website.
How do I know my website is responsive?
People connect to the internet with different devices. This reason implores us to test and see how our website displays on different devices. Our experience in this testing tells us how others feel when they access our site.
There are different ways to carry out this test. Let’s look at 3 of them.
Resizing the browser
The easiest way to test a website for responsiveness is to resize the browser window to different sizes to match different viewports.
Tablet Mode after Adjusting the Browser a Little
When doing this, we observe if there are rendering problems, and correct them at once.
Test in Different Mobile Phones
Though the browser resizing method helps, it will be better to test the site on real devices. You can use different mobile devices where you can perform different tasks.
I advise that you test your site using friend’s and family’s devices and see how your site renders on their devices. Also, perform different tasks and note how people who browse your site feel.
There is yet another method.
Use appropriate testing URL
These days, it’s easy to test your website for responsiveness. There are different websites that can help you do this, some of them include:
- Responsive Website Design Tester
- Screenfly | Test your Website at Different Screen resolutions
- Am I Responsive?
- Responsinator
- Responsive Device Testing
- Is Responsive
- First, visit any of the websites above;
- Enter the URL of your website.
- Test using different viewports.
Among these 3 methods, it will be best to test your sites using real devices. Do not rely on only the first and last methods.
Welcome to the last of the 3-course series in CSS (Cascading Stylesheets). In this course, we will discuss the following:
- how to work with generic and web fonts
- how to add animations to elements, and
- how to create responsive websites (web layouts)
Let’s get running, I can’t wait to start.
Responsive Web Layout using @Media Rule
As defined at the beginning of this course, a website is responsive if it adjusts perfectly to any device used to access it.
Remember that the flex, multiple columns and grid properties make building a responsive website easier these days. This is because they are responsive by default.
However, when using floats, and when we want to create breakpoints for different devices in our layout, we use the @media at-rule to make a website responsive.
Hence, we can wave flexbox and grid layouts and still create a responsive web layout using @media ruleset.
The viewport
The viewport is your screen size or the size of your browsing window. Viewport depends on the screen size of a device. Different devices have different screen sizes. Mobile phones have smaller screen sizes or viewport while laptops and desktops have larger viewports.
Viewports can be basically divided into 3:
- mobile phones (max-width: 768px)
- tablets and netbooks (max-width: 1024px)
- laptops and desktops (min-width: 1024px)
Traditionally, the iPhone and iPad view ports are used where:
iPhone has (min-width: 320px; orientation: portrait) and (max-width: 480px; orientation: landscape).
iPad has (min-width: 768px; orientation: portrait) and (max-width: 1024px; orientation: landscape).
Because devices have different viewports, it is important for us to ensure that our website adjusts to users’ viewport to create a good user experience.
For us to achieve this, we need to include a <meta> element in the <head> section of our HTML document with the name and content attributes as follow:
<meta name = “viewport” content = “width=device-width, initial-scale=1.0”>
The above code will tell the browser how to adjust the webpages depending on the user’s device-width.
Haven understood the basics; we shall begin our journey towards building a responsive web layout using @media ruleset. We shall bring the detail of @media rule in our next post.
Working with the Grid Layout in CSS3
The grid layout gave us a better way to create a responsive website. The flexbox layout is great but it has its limitations. In flexbox, items are laid out in one dimension.
In a grid layout, items are laid in two dimensions. The grid layout permits items to be laid out in columns and rows. It also gives room for space in between, called gutters.
In this module, we shall discuss:
- the grid system,
- how to create a grid layout,
- using functions in a grid layout,
- the grid lines, and item placement,
- the grid-area, and
- grid-template-area.
The grid system
The grid system is used to create a multi-dimensional and responsive website. To create a grid layout, we use the CSS declaration:
display: grid;
OR
display: inline-grid;
on the parent container.
Just like the flexbox, the grid layout will consist of the parent element and at least one child element.
When the display value of grid is applied on a parent container, all the direct descendants or children of that element becomes grid items.
But, unlike the flexbox, when the display property value becomes grid, the container becomes a grid layout with one column and row.
The direct descendants are not immediately transformed into a grid layout like the flexbox. They require that columns and rows be created for a complete grid layout.
Creating the grid layout
To create a grid layout, we do the following:
- First, apply a display property value of grid to the parent container.
e.g. article{ display: grid}.
- Define the number and size of the columns in the grid layout.
e.g. article{grid-template-columns: 250px 250px 250px 250px}
In the above, we defined 4 columns with a size (width) of 250px per column. You can also use auto and/or percentage (%) values to define the grid-template-columns.
Another important value to be used for grid-template-columns property is the fraction ‘fr’ unit. This unit is used to distribute available space into equal parts according to the specified value.
For example, if we use;
grid-template-columns: 1fr 2fr 1fr
It means to give one fraction of the space available each to columns 1 and 3 and 2 fractions to column 2. Hence, column 2 will be 2 times column 1 and 3.
- Next, use the grid-template-rows to define the height of each row in the grid container. For a container with one row you can use:
grid-template-rows: 200px;
For a container with two rows, you can use
grid-template-rows: 200px 300px;
- Finally, use the grid-gap property or just gap (not supported by all browsers) to specify the gap between the columns and the rows.
You may specify the row gap only with grid-row-gap (row-gap) and column gap with grid-column-gap (column-gap).
Example:
Lets’ look at an example embracing the above four properties:
Using functions in a grid layout
We shall discuss two functions that will be of importance when creating a grid layout. They are: the minmax() function and the repeat() function.
The minmax() function
When a grid layout is created, the content grows within the grid items automatically. But when we explicitly specify the row height (grid-template-row: 150px), the content may grow to overflow its size.
To avoid this, we may use the minmax() function to ensure that a minimum height is specified, while allowing space for the growth of content. We can be used with the grid-auto-row property to ensure that all rows height are assigned at the same time.
The repeat() function
The repeat() function is used to specify the number of times a column will be repeated. Including the size (width) of each column.
The function is used alongside the grid-template-columns as shown below:
Grid-template-columns: repeat(x, y)
where x = number of times to repeat a column and
y = size of columns to be repeated. y could be a single value or multiple values.
Example:
The above repeat() function states that 2 columns of sizes 1fr, 2fr should be created and be repeated twice in a row.
The first value of 2 indicates how many times the column created should be repeated. The second value specifies the size of the columns to be created.
The gridlines and item placement
The grid items in a grid container are arranged in column lines and row lines. Column lines are arranged from left to the right while row lines are arranged from top to the bottom.
The leftmost line is column line 1 till the rightmost line, while the topmost line is row line 1 till the bottom line, as shown below.
The line numbers displayed above help us to place contents in grid items. The line numbers are used to provide values for the following properties: grid-column and grid-row.
- grid–column: This property is used as a shorthand for grid-column-start and grid-column-end. The grid-column-start property is used to indicate where the grid-column started while the grid-column-end property is used to indicate where the grid-column
Therefore line numbers are used to determine the values of the grid-column and grid-row properties.
For Example, you can use:
grid-column-start: 1
grid-column-end: 3
OR
grid-column: grid-column-start / grid-column-end
written thus:
grid-column: 1/ 3
This means that the column begins at line 1 and ends at line 3. This will span 2 columns.
If you want only column 3 you may simply use 3 instead of 3/4.
- grid-row: This property is used as a shorthand for grid-row-start and grid-row-end. The grid-row-start property is used to indicate where the grid-row started while the grid-row-end property is used to indicate where the grid-row We can write it as follow:
grid-row-start: 2
grid-row-end: 5
OR
grid-row: grid-row-start / grid-row-end
Written as:
grid-row: 2 / 5
This means that the row begins at line 2 and ends at line 5. This will span 3 rows.
If you want only row 2 you may simply use 2 instead of 2 / 3.
What these imply is that to create a good layout, you may need to draw row and column lines. This will help you understand how to place your items in the grid.
Let us illustrate with the following.
Let’s create a grid layout with 7 column and row lines. That is 6 columns and 6 rows.
We can create our column layout by sharing them equally thus [repeat(2,1fr 1fr 1fr)]. This means that all the columns have equal size.
Let us now place items in this container using our HTML and CSS. We will add class to our block elements.
The final CSS and HTML will look like this. Please, take your time and go through the code to understand it better. Ask question where you are confused.
The grid-area and the grid-template-area
grid-area: The grid-area property can be used as a shortcut for the grid-row-start, grid-column-start, grid-row-end, and grid-column-end.
Let us illustrate with the HTML above.
grid-template-area: I believe you have understood how we use the grid-area property. Let us discuss the grid-template-area property.
In the grid-template area, instead of using line numbers to define the area cells will span, we use names.
The use of names to define grid-area is called grid-template-areas.
How does it work?
- First, we’ll define our grid container, say:
article{display: grid;}
- Second, we specify our columns. Remember, this depends on the layout you want for your website. Let’s assume a website with main content in the middle and two sidebars, one at the left and the other at the right.
Then we have:
grid-template-columns: 1fr 3fr 1fr; gap: 5px;
The above column definition has 3 columns with the middle column being 3 times the size of the first and the last columns.
Let us assume that we want a site layout that looks like this:
In the above layout, we will use the top row as the header row, the middle row will be the main content with two sidebars and the last row will be the footer.
- Define the grid-template-areas as follow:
grid-template-areas: "NavHeader NavHeader NavHeader" "LeftSideBar MainContent RightSideBar" "Footer Footer Footer";
Notice that each row is defined in three columns within double quotation as follow:
- “NavHeader NavHeader NavHeader” indicates that the NavHeader will occupy the entire row.
- “LeftSideBar MainContent RightSideBar” indicates a left sidebar, main content and right sidebar.
- Finally, we define the content cells individually.
When we combine the whole code, we have as follow:
When using the grid-template-areas, all cells of the grid container must be filled. If there is a need for a cell to be empty, use the “.” (full stop) to indicate such cell(s). Do not for any reason repeat an area in different locations (areas are unique in the grid layout).
Assignment: Create a web layout using a 12-column grid system
Conclusion
Frameworks that use the grid system usually use 12 columns or 16 columns grid system. Bootstrap, Zurb Foundation, etc use 12 columns while Titan and 960 Grid System use both 12 and 16 columns.
If you are using a 12 column grid system, then you will have 13 column lines.
So far, we have learned how we can alter the default flow of HTML elements using CSS. You can layout your website in a table, but this is not recommended.
If you wish, you can use float to layout your website. This requires the knowledge of @media at-rule to make your website responsive. We will cover this aspect in our next course “Building Responsive Website.”
The flexbox and grid layouts are responsive by default, but the grid layout win. However, you will need browsers that support HTML5 to use this layout for your pages. The good news is that major browsers support HTML5.
From what we have learned so far, you can be able to create an appropriate layout for your website.
The Flexbox Layout in CSS3
Flexbox (flexible box) is used to create a single-dimensional responsive webpage. Flexbox layout is one of the CSS layouts as has earlier stated.
In this module, we shall discuss in simple terms, how to use the flexbox layout in our webpages. Among what we shall discuss include:
- the flex container
- the flex-flow property
- the flex property
- the flex order property, and
- alignment of flex items
Let us start by learning how flexbox layout works on a webpage.
Working with Flexbox layout
The flexible box, otherwise called flexbox is used to create a one-dimensional layout for elements in a website. The dimension may be laid out in a row or a column.
In its simplest form, to apply the flexbox layout, we use:
display: flex
OR
display: inline-flex
We use display: inline-flex to create inline flex elements just like inline-block display value, earlier discussed.
This display property is used on the parent element such that the direct children of the element become flex items.
It is important to understand that clear, float and vertical-align properties do not work in flex items. That is, we do not use them in flexbox layout. Let us illustrate with this HTML code.
Note that we added display: flex; in the article element. There are two direct children of the article element in the flexbox layout, namely <div>. As a result, the output will be a two-column flexbox layout as shown below.
Secondly, if we have items that we want to appear in-line with text, we use the display property value inline-flex. To illustrate inline-flex in flexbox layout, add the following CSS to the HTML above.
ul{ display: inline-flex; }
After adding the CSS above, notice how the result displays.
The flex container
When applying flexbox layout, we have to differentiate between the flex container and the flex items.
The flex container is the parent element on which flex value is applied (e.g. the article element in the example above).
The flex items are the children of the flex container. They are the direct children of the flex container. In our example above, the <div> represents the direct children or flex items. Flex items may include different elements, provided they are direct children of the flex container.
The flex-flow Property
One of the properties of the flexbox layout is the flex-flow. The flex-flow property controls the flex-direction and flex-wrap properties.
- The flex-direction is used to control the direction of the flow of flex items. It has the following values
- row (flow left to right),
- row-reverse (flow right to left),
- column (flow up to down) and
- column-reverse (flow down to up).
The row value is the default, on which elements are laid out in rows.
- The flex-wrap property is used to determine if the flex container will permit multiple rows or not. Remember that flexbox layout defines unidirectional items. Items could be laid in rows or columns.
To permit multiple rows, we use flex-wrap: wrap declaration.
Flex-wrap has the following values
- wrap,
- nowrap, and
- wrap-reverse.
We may use the flex-direction and flex-wrap properties individually, but it is advised to use the flex-flow property. For example, instead of:
flex-direction: row-reverse; and
flex-wrap: nowrap;
we use:
flex-flow: flex-direction flex-wrap
flex-flow: row-reverse nowrap;
Let us illustrate with the following:
Notice that the output displays 6 columns. In a flexbox layout, as you increase the number of flex items, the number of columns increases. Consequently, the column width continues to decrease.
To solve this problem, we use the flex-flow property in our flexbox layout as follow:
article{ display: flex; /*flex-flow: row wrap; } div, ol{ flex: 300px; }
NB: In the CSS code Remove the ‘/*’ that appears at the beginning of flex-flow to display wrapped flex items.
The flex property
Did you notice that before our flex-wrap takes effect we added the flex property in the <div> and <ol> elements.
The flex property is used to control the dimensions of the flex items in a flexbox layout. It is usually used as shorthand for the following properties: flex-grow, flex-shrink, and flex-basis.
- The flex-grow property is used to specify how much space a flex item will occupy within the available space. It has a unitless value of 0, 1, 2, … its default value is zero.
- The flex-shrink property is used to specify how much space a flex item will leave for other flex items within the available space. That is, how much will an item compress itself to give space for other items within available space. It uses a unitless value of 0, 1, 2, … its default is zero.
- The flex-basis property is used to specify the main size of a flex item. Its value can be auto or be specified as a unit of length, say, pixels.
You can specify each property individually or use the flex shorthand property to specify them. To use the flex shorthand, do the following:
flex: flex-grow flex-shrink flex-basis; e.g. flex: 1 0 300px;
Let us illustrate.
In the flexbox layout above, elements with the class “sm1” have flex:1, while elements with the class “sm2” have flex:2. This means that flex items with sm1 will have equal sizes; while flex items with sm2 will have 2 times the size of the sm1 items.
You may decide to have a fixed size for a particular flex item while the remaining space is shared among other items within the container. To do this, specify a flex-basis for that flex item.
This is what we did with flex-items with classnames “sm3” and “sm4”. We allocated flex:1 for items with sm4 and flex: 400px for items with sm3. See the second section in the example above.
The flex order property
This property is used to alter the position of a flex item within the flex container in flexbox layout. We do this without altering the default code order.
The value of the order property must be an integer, positive or negative. The flex items with the least value are placed first in the order; while flex items with the same value are placed in their default order.
The default value for all flex items is 0.
As Example, consider the following HTML and CSS:
Notice how the position of the <a> elements where altered in the output.
Alignment of flex items
To align flex items within the flex container, we use four different properties, namely: justify-content, align-content, align-items and align-self.
The justify-content property is used to align flex items along the main axis of the flex container. This is possible if there is still available space along the axis.
This property has the following values:
- flex-start (flex items are placed at the beginning of the main axis; this is the default value),
- flex-end (flex items are placed at the end of the main axis),
- center (flex items are placed at the middle of the main axis),
- space-between (flex items are evenly distributed along the main axis with equal spaces between the items. The first item is placed at the beginning and the last item placed at the end), and
- space-around (flex items are evenly distributed along the main axis with equal spaces from the start of the items to the end of the items. Here, the equal spaces are left at the beginning and end along of the flex items).
Example, consider the following HTML:
Play with the different values of justify-content and see the results.
The align-content property is used to align flex items along the vertical or cross-axis of the flex container. This is especially useful when there are multiple columns within the flex container.
It has the following values:
- flex-start,
- stretch (flex items are shared equally between columns and rows vertically; this is the default value),
- flex-end,
- center,
- space-between, and
- space-around.
Example
Play with the other values of align-content and see the results.
The align-items property is used to align flex items vertically within the flex container.
The align-self property is used to align flex-items vertically within the flex-item. When both align-items and align-self properties are used, the align-self overrides the align-items property.
Both properties have the following values:
- flex-start,
- flex-end,
- center,
- baseline (aligns flex items along the baseline of the flex item(s) with the largest font size), and
- stretch.
Example
NB: You can perfectly centralize the flex items in a container by using justify–content: center, and align-items: center.
With this we come to the end of flexbox layout. Remember to go through the float and position property if you have not learnt of it. Next week, we shall look at working with the grid layout.
The Float Property and Position Property in Web Layout
The float property and the position property can also be used to alter the default block flow of HTML elements. In this section, we shall discuss the float property, the clear property, z-index property, and the position property.
The Float Property
The original purpose of float is to allow images to float around text. Images can float either to the left or to the right. That is by wrapping text around images.
But we can use the float property to create multiple columns in a webpage. Note that elements can only be floated if they are not absolutely positioned.
In its simplest form, the float property has the following values:
- left, right, none and inherit.
The left value allows elements to be positioned to the left of its container. While the inherit value permits elements to use the float property of its parent.
Let us illustrate with this simple example:
Check the output before applying float property, then the output after applying the float property.
Let’s now apply the float property by simply adding the following CSS below:
#myfloatimg{ float: left }
[Result is shown in the second section of the above example.]
Check the output after applying the float property:
You can also change the float property value to the right, to let the image float to the right. While the text wraps around it.
Creating Columns and Boxes with the float property
You can use the float property to create columns and box layout in a webpage. Let us illustrate with the following example:
NB: When you use float to create boxes, you will have unequal boxes. This can be controlled by specifying the height property for your boxes.
The clear property
When an element has the float property, the element following it will be stacked around it. To stop subsequent element from floating, we use the clear property.
The clear property has the following values: left, right, both, none and inherit.
Let us illustrate with this example:
The Position Property
Another way to alter the normal flow of the HTML elements is by using the position property. In this section, we’ll be discussing the position property.
The position property is used to specifically place an element in a given location within a site layout. We have earlier discussed that element in an HTML document flow in a block form.
Subsequent block elements follow the previous ones in a normal layout flow. But using the position property, we can alter this flow by specifying where a particular element will be placed in the webpage layout.
The position property has the following values: static, relative, absolute, fixed, and sticky.
Before looking at the values, let us first look at how an element is placed in a webpage in the x and y-coordinate.
Positioning an element
In a page layout, an element can be positioned in relation to the four margins of the page. They include the top, right, bottom and left of a page.
Hence, while positioning an element, we may use the top, right, bottom and left properties to define the actual location on-page. These properties are associated with the position property, without which they will not work.
These properties can take on values of any unit of length, say, px, cm, mm, in, etc. e.g. top: 200px; left: 150px;
The top property moves the element down from the top based on the value specified.
E.g. top: 20px will move the specified element 20pixel down from its present location.
Similarly, the bottom property will push the element up from its present location to the tune of the specified length.
The left property will move the specified element from left to the right.
And, the right property will move the specified element from right to the left in the tune of the specified length value.
In this case, the value of top: 0; left: 0; means top left position of the page.
Example
The z-index Property
Haven discussed the top, right, bottom and left properties, it will be worth mentioning the z-index property.
The z-index property affects the stacking of positioned elements on top of each other. We use the z-index property to specify which element should appear on top of the other when more than one element is stacked together.
The z-index property takes on unitless value such that the element with a higher value will be on top of the element with a lower value. The default value is auto which is the same as 0.
Example
Consider the following HTML and CSS example.
The output shows that each <p> element is stacked on top of each other in their order in the source code as shown below.
We can change this order by applying the z-index property to the first paragraph with the id=“fir”.
NB: id was changed to firz for purpose of uniqueness.
This is shown in the second <section> of the example below:
Notice the z-index in the #firz. The z-index will bring forward or take backward a particular element in the z-coordinate.
Specifying the Position Property values
As noted above, the position property has 5 values: static, relative, absolute, fixed and sticky. Let us look at each of these values and how they affect your elements.
position: static
One of the values a positioned element can take is static and this is the default value of every element in the HTML document.
Elements with their position value set as static simply mean that the element will follow the normal document flow.
There is no difference between such elements and elements in the normal flow. Here, the top, right, bottom and left properties are of no effect.
Example
In our HTML above, we changed the position value in the CSS to static. The result will be as follow:
position: relative
Elements which their position value is set to relative will behave like elements which their position value is set to static.
This means that they will follow the default flow of elements in the HTML document, but with an exception. The exception is that the top, right, bottom and left properties work with this position value.
Hence, when an element is relatively positioned, you can alter its position with the top, right, bottom and left properties. Other elements within the document flow are not affected.
Example
In our HTML above, change the position value in the CSS to relative. The output will now look like this:
position: absolute
When an element’s position property value is set to absolute, that element is usually located at the top: 0; left: 0; in relation to its nearest positioned parent, if and only if this parent’s position is not static.
If the parent’s position is static, then the element will be positioned in relation to the browser window.
Absolutely positioned element is completely removed from the document flow, and subsequent elements would close up the gap left by such element.
The top, right, bottom and left properties work fine here; also, absolutely positioned elements scroll with the page.
Let us illustrate:
The first paragraph element is completely taken off the normal document flow as shown below:
position: fixed
An element with this type of position behaves like an absolutely positioned element with few exceptions.
- The position is relative to the browser’s viewport rather than parent’s element
- It does not scroll with the page. When pages are scrolled it remains at a fixed position.
Example:
Output: try and scroll, you’ll notice that the fixed <nav> does not scroll with the page.
position: sticky
This type of positioned element is a hybrid of fixed and relative positioning. This is because it acts like a relative positioned element until the page is scrolled to some extent. When the element with a sticky position value reaches the top scrolled page, it acts like a fixed positioned element.
Example:
The output should look like this. Scroll to test the result. This is where we will end today’s post. Next week, we shall look at the flexbox layout.
The 123 of CSS Layout: Table and Column layouts
CSS layout deals with the arrangement of HTML elements in a webpage or website. Here we will learn how to position the contents of our HTML outside its normal flow. Particularly, we are going to discuss table CSS layout and multiple CSS layout.
The Default Flow
When we write our HTML code, elements are by default stacked on each other in a normal flow. Let us illustrate this with the HTML code below.
From the output above it is obvious that block elements are stacked according to the order of the code.
However, CSS layout will help us to understand how we can deviate from this flow and impose the layout we want. This will help us create a better and more beautiful appearance of our site.
To impose our desired CSS layout, we will need to manipulate the CSS code using any of the following methods:
- Display property: We have discussed three classes of the display properties including block, inline and inline-block. Other display properties values that can be used to change our sites layout include flexbox CSS layout, grid CSS layout, and table CSS layout. We shall discuss each of them shortly.
- Floats: Another property that will help us alter the normal flow of our site layout is the float We can use the values of this property to decide which side we can position an element in our site.
- Position property: This property is also important when placing elements on a website. With the position property, we can choose where to locate and how an element should behave in the site CSS layout.
- Multi-column: Finally, we can also use the multi-column property to layout elements in columns depending on what we want to achieve.
We will walk through each of these properties. Let’s start with the table CSS layout.
Building CSS Layout with HTML Tables
The table is an old method of laying out a webpage. Table CSS layouts were used before the advent of Cascading stylesheets. It is therefore not advised to use it, basically, because it is not responsive by default.
Using a table, we can position elements at specific points in the table row. But this method is no longer favored in modern web designing.
We have already discussed how to work with HTML tables. If you are new to HTML tables, kindly visit here for the complete tutorial.
Based on what is learnt, we can now use the <thead>, <tbody> and <tfoot> elements to create layout for a webpage.
This does not mean that you should use it. We are simply showing an example of how to use it for the sake of knowledge.
The code shown below illustrates how to create a webpage layout using a HTML table.
Multiple Columns CSS Layout
Here, we shall discuss how to layout our contents in more than one column. The multiple column features allow you to divide your webpage contents into more than one column. This feature mimics what is popularly seen in newspapers and magazines.
Creating columns
To create multiple column content, we use any of the following properties: column-count, or column-width.
column-count: The column-count property is used to specify the exact number of columns you want for your page contents. It takes on a unitless value of 0, 1, 2, … When the column-count property is used, the browser itself will work out the gaps between the columns.
Let’s illustrate using our last HTML example. Simply add the following CSS to the section: margin: 0 auto; column-count: 4;
The whole CSS and HTML should be:
column-width: We use the column-width property when we want a particular width for our columns. However, if the container could not accurately utilize the width, the remaining width will be shared among the columns. This means that the actual width size may be larger than the specified width size. The column-width property takes on a length value (px, in, cm, em, etc).
Let us now change our CSS above to the following:
NB: Notice that using column-width makes your webpage mobile friendly than using column-count property.
Customizing columns
The columns we created above defaults to the browser’s style. Let us now discuss some properties that will help us style the columns we have created. This is necessary if we do not want the columns to default to browser’s style.
Some of the properties we might set to our columns are Column-gap, Column-rule, Column-fill, and Column–span.
column-gap: This is used to set a gap between columns. The value can be a length of px, em, cm, etc.
column-rule: This property is used to add vertical lines between the columns. It works like the border property. It is used as a shorthand for the column-rule-width column-rule-style and column-rule-color.
It takes on the same values as the border property. E.g. column-rule: 3px solid red;
The column-rule-style can take on any of the following values: dotted, solid, double, dashed, inset, groove, outset, ridge and none.
The column-rule-width takes on length values while the column-rule-color takes on color values.
NB: Column-rule-width should be less than or equal to column-gap.
Let us illustrate:
column-fill: This property is used to specify how the contents of your column is filled. Its values include:
- balance (default value, here contents are equally filled),
- auto (here columns are filled sequentially. The later columns may not be fully filled).
column-span: This property is used to indicate the number of columns an element should cover. It can take on any of these values:
- none, and
- all.
To illustrate the above properties, let us add the following CSS to our HTML above.
NB: All browsers do not support column-span property. We used the Chrome browser.
Basic Introduction to The CSS Box Model
In CSS web layout, each HTML element is represented in a rectangular box. Because element is a box, to apply CSS to selected elements, we assume some of the box properties. This is why we have “the CSS box model”.
In this module, we shall look at the content box, content overflow, background properties, shadow effects and classes of boxes. There is a lot to cover in this module.
Let us quickly look at the content box of a selected element and its properties.
The Content Box
The CSS box model is the core or primary component of every CSS web layout. In its simplest form, the CSS box model represents every HTML element in a rectangular box. Each box element is made up of the following properties:
- the margin,
- the border,
- the padding, and
- the content.
These properties are built around the element with the content being the innermost property and margin being the outermost property. These properties are adjusted in CSS by assigning values to them.
Let us illustrate the CSS box model for a clearer understanding.
From the image, we notice some properties. Let us go through them individually.
Content height and width: This is the actual height and width of the element’s content. We use the height and width properties to set their values. we may also use the min-height, max-height, min-width, and max-width properties to set values for the content based on constraints.
Note the following concerning content height and width:
- content width does not include the padding and the border. Hence, to get a total box width, we will need to add up the following: width + padding-left + border-left + padding-right + border-right = total width.
If we really want to ensure that the overall box width, including padding and border, is of a certain percentage, say, 60%, then we will use the box-sizing property instead of width property. E.g. box-sizing: border-box;
- To set the height property, do not use percentages, say, 60%, instead use absolute value, like, 350px. This is because box height takes on the height of the CSS box model content.
Padding: This is usually the distance between the edge of the content and the border as shown in the image above. We may use the padding property to set equal value for all the four sides or use the padding-top, padding-right, padding-bottom, and padding-left to set individual side’s padding respectively.
Border: The distance between the margin and the padding is occupied by the border. By default, border values are set to 0, which make them invisible. To set a border, we may use the border property. This will set a border for all the four sides. However, we may decide to set a border for each side using: border-top, border-right, border-bottom, and border-left.
When setting the border property, use the format:
div { border: border-width border-style border-color; }
where border-width (e.g. 5px), border-style (e.g. solid), and border-color (e.g. red).
Thus, we have:
div{ border: 5px solid red; }
When background-color or background-image property is added to an element, it usually extends to the outer edge of the border. This can be controlled using the background-clip property.
Margin: This is the outermost layer in the CSS box model. It surrounds the element and helps to push out other elements in the layout. We can use the margin property to set its value or use the margin-top, margin-right, margin-bottom, and margin-left to set individual side properties.
Example:
p{ margin: 7px; } p{ margin: 5px 3px 5px 3px; }
The second example sets the margin-top and margin-bottom to 5px, and margin-right and margin-left to 3px.
If you want to centralize the content of an element, use the auto as value for left and right margins.
E.g. div{margin: 5px auto;}
This will set 5px as margin for the top and bottom and auto for the left and right, thereby centralizing the content.
Let us illustrate the CSS box model with the following simple code:
Content Overflow in the CSS Box Model
There are times we may set absolute value for our content boxes using the width/ height property. And when the size does not contain the content of the box, the content will tend to overflow the box.
For example:
In our above HTML code, let us tweek our CSS as follow:
article{ width: 50%; height: 150px; padding: 10px; border: 3px dotted coral; margin: 15px 10px 20px 15px; }
The output will be like this:
Notice that part of the content could not contain in the box. We call this overflow.
How do we handle such a situation?
By default, when content overflows, the visible value is used to show the content outside the box. However, we can control this using the overflow property.
The overflow property has the following values:
auto: If the content overflows, the overflown content will be hidden and scroll bars will be shown so that users can scroll through the content. For example, add overflow to the above CSS to have the following:
article{ width: 50%; height: 150px; padding: 10px; border: 3px dotted coral; margin: 15px 10px 20px 15px; overflow: auto; }
Edit the above code in JSFiddle to see the output.
hidden: This value when used will completely hide the overflown content.
visible: This is the default behavior. It shows the overflown content outside the box.
The Background Property
Background Clip Property
This is used to control how background-color and/or background-image is applied to an element in the CSS box model.
By default, background-color and background-image extends to the edge of a border. This can be controlled using the following declarations:
background-clip: value;
value can be any of the following: border-box; padding-box or content-box.
Background-clip: border-box: This is the default. Background color and image extends to the edge of the border box.
For example:
<div> <p class="test" id="tests"><u>It is not a new thing that</u> <span>politics</span> in <span>Nigeria</span> is for the risk takers. This tells why people could leave their current jobs and business to pursue <span>politics</span>. </p> </div> CSS div{ width: 70%; padding: 10px; border: 3px dotted green; margin: 15px 10px 20px 15px; background-color: darkblue; background-clip: border-box; }
Background-clip: padding-box: When this declaration is used, the background color or image will extend to the edge of the padding only.
Changing our CSS above, we have:
div{ width: 70%; padding: 10px; border: 3px dotted green; margin: 15px 10px 20px 15px; background-color: darkblue; background-clip: padding-box; }
Notice that the background color has separated from the border.
Background-clip: content-box: This will ensure that the color or image covers only the content box. Changing the CSS, we have:
div{ width: 70%; padding: 10px; border: 3px dotted green; margin: 15px 10px 20px 15px; background-color: darkblue; background-clip: content-box; }
The above CSS changes were combined in the HTML and CSS codes below.
Adding background
A background is a color or image sitting behind the content of an element. It usually adds beauty when the element is displayed.
Before adding a background to an element, we should understand the following properties:
background-size: which is used to dynamically resize a background image.
background: We use the background property to apply background to an element. It is used as a shorthand to specify the following properties which can also stand on their own.
- background-color (used to set a solid color),
- background-image (used to set a background image or linear-gradient),
- background-position (used to position the background within the element),
- background-repeat (used to specify if a background should be tiled or covered), and
- background-attachment (used to identify the behavior of a background).
To use a background property, we specify it thus:
background: background-color background-image background-repeat background-position background-attachment
which gives us
background: rgba(35,0,0,0.5) url(‘cakes.png’) no-repeat right bottom fixed;
You will understand the above code later in this tutorial.
Applying multiple background
You can also use the background property to apply multiple backgrounds to an element.
For example:.
background: linear-gradient(to top, yellow, blue, green), URL(“cake.png”);
The images or background color will be applied in the following order:
- the first (linear gradient) will appear on the top,
- while the second (image) will be behind it.
If you have up to 4 images, then the first will appear at the top and the last behind them all.
NOTE: When a background image is used, by default, it tiles the image in the background. But this depends on the size of the image used.
For example, if the image is large, it will cover the entire space, if the image is small, it will be tiled by default.
Let’s look at some of the properties highlighted above individually.
Background Repeat property
We can use background-repeat property to remove tiled images in the background.
The background-repeat property has the following values:
- repeat (image is tiled)
- no-repeat (image is not tiled)
- repeat-x (image repeated along the x-axis)
- repeat-y (image repeated along the y-axis)
Try using each of the values and see what happens.
Background-position
Aside from background-repeat, we can use background-position to specify the location of the image inside the element. The background-position property can have any of the following values: pixels, percentages, or keywords such as: right center, left, center, top and bottom.
Linear gradient
We may use linear-gradient to apply background. In this case, we will need to specify how the gradient will be applied by using keywords like: to top, to bottom, to left, to right, to top left, etc. We may also use deg such as 40deg, 180deg, etc.
When applying color mixture, we can also specify values for the color using percentages or pixels.
For example:
nav{ background-image: linear-gradient(to bottom left, yellow, green 35%, blue 45px); } nav a{ color: #ff0000; } div{ background-image: linear-gradient(75deg, red, blue, orange 5em, coral, purple); }
background size
When dealing with background-image, we may use background-size property to resize the image so that it could fit within the element. This can be especially useful for image icons.
For example:
nav{ background-image: linear-gradient(to bottom left, yellow, green 35%, blue 45px); background-size: 100px 100px; } nav a{ color: #ff0000; }
We may also use the background-attachment property to control if the background scrolls when the content scrolls. The background-attachment has the following values: scroll, fixed and local.
Adding border
We have learned how to add borders under content box. Here, we will look at how to make our borders have a rounded edge, and how to use an image as a border.
border-radius: The border-radius property is used to create a rounded border around an element in the CSS box model. To use this property, we do this:
border-radius: value in pixels (This will apply the same value to all corners).
e.g. border-radius: 15px;
border-radius: top-left top-right bottom-right bottom-left
For example, using our HTML above, we apply the following CSS:
nav{ background-image: linear-gradient(to bottom left, yellow, green 35%, blue 45px); background-size: 100px 100px; border-radius: 20px; } nav a{ color: #ff0000; } This will apply equal border-radius to all corners. nav{ background-image: linear-gradient(to bottom left, yellow, green 35%, blue 45px); background-size: 100px 100px; border-radius: 20px 10px 5px 25px; }
This will apply unequal border-radius to the corners.
border-image: This property is used to apply the image as a border in the CSS box model.
Applying border-image requires the use of the following additional properties:
background-clip: padding-box, this will separate the background from the border area. Then we need the following properties to make the border-image work:
border-image-source: The source of the image
border-image-slice: to specify the size of the image slice. It can take one, two, three or four values. You can use a unitless value, say, 20.
border-image-repeat: This will tell how the image will fill the border. It has the following values: repeat, stretch, round, and space.
Let us illustrate with the following CSS on our HTML above.
nav{ background-image: linear-gradient(to bottom left, yellow, green 35%, blue 45px); background-size: 100px 100px; border: 20px solid coral; background-clip: padding-box; border-image-source: url("Cakes.jpg"); border-image-slice: 20; border-image-repeat: space; } nav a{color: #ff0000;}
Try changing the value of border-image-repeat to see the differences.
The shortcut for using border-image is as follow:
border-image: border-image-source border-image-slice border-image-repeat
e.g. border-image: url(‘Cakes.jpg’) 20 stretch
The output is as follow:
Shadows effect
Apply drop shadows to your boxes using the box-shadow property and to your texts using the text-shadow property.
The box-shadow and text-shadow properties have the following values:
- horizontal offset,
- vertical offset,
- blur radius and
- base color.
Each of these values can take normal CSS lengths in pixels. For example:
box-shadow: horizontal_offset vertical_offset blur_radius base_color
text-shadow: horizontal_offset vertical_offset blur_radius base_color
e.g. box-shadow: 5px 4px 3px green;
text-shadow: 2px 3px 2px blue;
Using our HTML code above, let us apply shadow effects on the elements:
You can also apply multiple shadow effects to your texts and boxes by stacking them together, separated by a comma.
E.g. box-shadow: 2px 3px 1px red, 1px 1px 2px blue
To add internal shadow effects, we use the keyword inset before the values.
E.g. box-shadow: inset 3px 3px 2px red
The filter property
When we apply shadow effects, the drop shadow usually follows the rectangular square of the box.
However, we can make the shadow follow the exact shape of the box by applying the filter property together with the drop-shadow() function.
In our example above, let us apply drop-shadow() function to filter out the shadow effect.
Classes of CSS Boxes
CSS boxes can be classified into 6 based on how they are displayed. To represent them we use the display property. They include inline, inline-block, block, flex, grid and table.
Using the display property, we can tell the boxes how they will render or be displayed in a CSS layout. Though the display property has other values, the following 3 are most common, namely: block, inline, and inline-block.
display: block – When block is used as a display property value, then the element with the value will begin on a new line and occupy the entire horizontal line.
All other successive elements will be pushed to the next line accordingly. Hence, this will create boxes of stacked elements on each other. Blocks can be sized using height and width properties. For example:
Notice that after the application of the display: block, each <a> element occupied the entire horizontal line.
display: inline – This type creates a continuous flow of text without line breaks. When display is inline then subsequent inline elements appear in the same horizontal line with each other and flows with normal text flow.
Heights and widths properties do not have effect on such block elements with inline display.
From the above HTML and CSS code, we can change the display to inline and have the following output.
display: inline-block: This type also creates a continuous flow of text on the same horizontal line without line breaks. But each block element maintains its block integrity. Hence, each block element can be sized with the width and height properties.
Let us change the display value to inline-block. In the output, there is no appreciable difference, but a closer look at the block elements will show that each block maintains its integrity. They will not flow with the text unlike with the inline value.
CSS3 Pseudo-Class Selectors and Pseudo Elements
Pseudo-Class Selectors
When users begin to interact with your website, the state or position of some elements may change. In order to apply CSS styling based on the state of an element, owing to users’ interaction, we use the pseudo-class selectors.
For example, when you create a link, it renders as blue underlined text. We can use pseudo-class selectors to style the link when it is hovered or when the link is visited (i.e. clicked on).
So, when a user points a mouse over a link, it is in a hovered state. Also, when a link is clicked it is in a visited state.
Pseudo-class selectors can also be applied based on the position of an element within the document.
When applying pseudo-class selectors to an element, we must always precede the class with a colon “:”.
For example, a:hover{…}.
There are different pseudo-class selectors for different purposes. We will examine some of them in alphabetical order. In this examination, we will define the enlisted pseudo-class selectors and their purposes.
In some cases, we give examples. Let us go through each of them briefly. Before you continue, checkout our previous posts on CSS syntax and Selectors.
:active This is used to style elements such as link “a” and “button”. It applies to elements when a mouse is pressed on them. However, styles in : active will be overridden by styles in other link pseudo-class selectors such as: link, hover and visited.
In all, : active can come after the above pseudo-classes in the order: LVHA.
Example
a:active{ color: green; text-decoration: none; }
:checked This group of pseudo-class selectors is used to style options in a select element. And items in an input element of type radio and/or checkbox. The style will render when any of these items are selected.
Example
input[type= “radio”]:checked{ color: orange; } input[type=“checkbox”]:checked{ color: lime; } option:checked{ color: blue; }
:default This is used to style default form elements in a group.
For example, it will match the input of type radio or checkbox, if they are checked by default.
Input:default{ color: red; box-shadow: 0 1px 1px 0 silver; }
:dir() Used to style element based on the text direction, which could be (rtl) or (ltr)
:disabled Used to style disabled input element. For example,
input[type= “text”]:disabled{ background-color: yellow; }
: enabled Used to style any element that is enabled, that is, an element users can interact with.
Example:
input:enabled{ color: darkgreen; }
:empty Used to style elements that has no children at all, i.e. completely empty element – no white space, no comment.
<p></p> <div></div>
The above elements are empty. To style it, simply write:
p:empty{ background-color: coral; }
: first This is usually used when setting @page ruleset to represent the first page when printing a document. e.g.
@page:first{ margin-left: 20%; }
:first-child This group of pseudo-class selectors is used to style the first element specified among its siblings in the group. To illustrate, we have:
In this example, the first paragraph in the two divs will be styled because each is the first child of each div.
In the second example above, only the first paragraph will be styled because the paragraph in the second div is not the first child.
NOTE: The code embedded above has examples for the :first-of-type, :last-child, and :last-of-type. Click on the HTML and CSS tabs respectively to study the codes.
:first-of-type This type of pseudo-class selectors is used to style the first element of the specified type among a group of sibling elements in each divisional section of an HTML document.
E.g.
<!-- Html code --> <div> <p>…</p> <p>…</p> </div> <div> <p>…</p> <p>…<p> </div> /*CSS Code */ p:first-of-type{ color: purple; }
The above style will apply to the first <p> element in each of the <div>s
: fullscreen Is used to style any selected element in a fullscreen mode. That is when in a fullscreen mode, the selected elements are styled to the specified CSS code.
: focus This is used to style input elements that are selected or brought to focus, either by mouse click or by keyboard tab.
<!--Example --> input:focus{ color: blue; }
:focus-within This type of pseudo-class selectors is used to style an element whose one of its descendants has received a focus. For example, we can style a form object when one of its input elements receives a focus.
Example
In the above example, notice how the form background changes to green immediately you selected any of its controls.
NOTE: The above example has examples for other pseudo-class selectors like :in-range, :invalid, and :lang. Click the HTML and CSS tabs to study the codes.
:hover This is used to style an element when a user places mouse over the element or points at the element.
h1:hover{ background-color: #00ff00; }
:in-determinate When the state of any form input element is indeterminate, then we use the style:
input:indeterminate{ color: red; }
:in-range This is used to show that the values in the input element is within the limits specified by the min and max values.
See example above.
:invalid This is used to highlight form field elements that does not validate. It is basically used to highlight errors. See example above.
:lang() This is used to style elements based on the language code. See Example above.
:last-child Just like the first-child, this is used to style the last element in a group of elements. See illustration example above (under :first-child).
In the example, the last paragraph in the two divs will be styled because each is the last child of each div.
In the second example above, two of the paragraphs will be styled because the paragraphs are the last child of each div.
:last-of-type This type of pseudo-class selectors is used to style the last element of the specified type among a group of sibling elements in each divisional section of an HTML document. See example above.
HTML: <div> <p>…</p> <p>…</p> </div> <div> <p>…</p> <p>…<p> </div> CSS: p:last-of-type{ color: coral; }
The above style will apply to the last <p> element in each of the <div>s
: left This is usually used when setting @page ruleset to represent the left-hand pages when printing a document. Example:
@page: left{ margin: 2in 2in; }
:link This is used to style the <a>, <area> or <link> elements that has not been visited. Example:
HTML Code: <p>The great tutorial was first shown <a href= https://www.kmacims.com.ng>Here</a></p> CSS Code: :link{ color: green; text-decoration: none; }
:matches()/ :is()/ :any This type of pseudo-class selectors is used to create large list of selector elements. We use it to style an element that matches the list of elements within our selection. If your browser is not compatible with :is and :matches, you can use the backward compatibility :-webkit-any (for chrome) and :-moz-any(for mozilla).
For example, to style a paragraph that appears in any of <div>, <section>, or <article>, when in is hovered, we can do the following:
:is(div, section) p:hover{ color: red; } :matches(div, section) p:hover{ color: red; } :-webkit-any(div, section) p:hover{ color: red;} :-moz-any(div, section) p:hover{ color: red; }
:not() This kind of pseudo-class selectors is used to style elements that are not in the list of selectors specified by the :not(list of elements).
For example,
:not(div){…}
will select elements that is not a div. You may also specify a class or id within the :not.
:nth-child() This kind of pseudo-class selectors is used to style an element based on its position in a group with its siblings, when counting from the top.
The nth-child uses the following keywords and notations:
odd: Is used to represent odd siblings, e.g. 1, 3, 5, 7, etc
even: Is used to represent even siblings, e.g. 2, 4, 6, etc.
An+B: Is used to represent siblings, where A and B must be integers, and n begins from 0, 1, 2, …
Example:
<div> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> <p>Paragraph 4</p> </div>
There are 4 paragraphs, so when we say, :nth-child(2n), it will select every second element among the group of its siblings.
However, if we say, p:nth-child(2), then it will select every <p> element that is second among group of sibling elements.
For example, in HTML table styling, we may use the following:
tr:nth-child(odd) OR tr:nth-child(2n+1) for odd rows
tr:nth-child(even) OR tr:nth-child(2n) for even rows
:nth-child(3) for the third element
:nth-child(3n) for multiples of 3 elements, say, 3×1=3, 3×2=6, 3×3=9, etc
:nth-child(3n+2) for multiples of 3 + 2 elements, in a progression, say, 3×0 + 2 = 2, 3×1 + 2 = 5, 3×2 + 2 = 7, etc
:nth-child(-n+4) for the first four elements, say, -0+4=4, -1+4=3, -2+4=2, -3+4=1.
:nth-child(n+3) :nth-child(-n+6) for a range beginning from the 3rd element to the 6th element.
Let us illustrate with this example:
:nth-last-child() This is the same as the nth-child. The difference is that we count from the bottom to the top. Everything applicable to the nth-child is also applicable here, but count from down up.
:nth-last-of-type() This kind of pseudo-class selectors is used to style the matched element of a specified type, depending on their position in the document, but counting from the bottom. The type is an element, say:
tr:nth-of-type(2n+1){...} p:nth-of-type(n+3){...}
:nth-of-type() This is used to style the matched element of a specified type, depending on their position in the document, but counting from the top. The type is an element, e.g.
tr:nth-of-type(2n){...} p:nth-of-type(n+3){...}
:only-child This kind of pseudo-class selectors is used to style an element in the HTML document that has only one child without siblings. It is the same as using any of: :first-child, nth-child(1) or nth-last-child(1).
HTML: <div> <p>This is the only child of a paragraph in this div</p> </div> <div> <p>This is the first paragraph or <span>first child</span></p> <p>This is the second paragraph</p> <p>This is the last paragraph</p> </div> CSS: p:only-child{ color: green; }
The above example will style the <p> element in the first div.
:only-of-type This is used to style an element in the HTML document that has only one child of a particular type. It may have siblings, but not of the same type. For Example;
HTML: <div> <p>This is the only child of a paragraph in this div</p> </div> <div> <p>This is the first paragraph or <span>first child</span></p> <p>This is the second paragraph</p> <p>This is the last paragraph</p> </div> CSS: p:only-child{ color: red;} /*will style <p> in the first div only>*/ span:only-child{ color: purple;} /*will style the <span> element in the second div only*/
:optional This kind of pseudo-class selectors is used to select and style <input>, <select> and <textarea> elements that are optional when submitting a form. Remember that an input element is optional if it does not have the required attribute set to it. e.g.
input:optional{ border: green; background-color: blue; }
:out-of-range We use this kind of pseudo-class selectors to select and style input element that have their values outside the values specified by the min and max attributes. For example;
<label for=“age”> Enter age: </label> <input id=“age” type=“number” min=“10” max=“25” placeholder=“Enter age between 10 and 25”> CSS: input:out-of-range{ color: red; border: 1px solid red; }
:read-only We use this kind of pseudo-class selectors to select and style input and textarea elements that cannot be edited by the user. For example:
input:read-only{ background-color: silver; } input:-moz-read-only{ /*backward compatibility for Mozilla browser*/ background-color: silver; }
:read-write We use this kind of pseudo-class selectors to select and style input and textarea elements that can be edited by users. It can also be used in <p> elements with the
contenteditable=“true” attribute.
Example:
input:read-write{ background-color: yellow; } input:-moz-read-write{ background-color: yellow; }/*backward compatibility for Mozilla browser*/
: required We use this type of pseudo-class selectors to select and style input, select and textarea elements that have the required attribute. E.g.
input:required{ border: blue; background-color: green; }
: right We usually use this when setting @page ruleset to represent the right-hand pages when printing a document. e.g.
@page:right{ margin: 2in 2in; }
:root We use this type of pseudo-class selectors to select the root element in a HTML document. This is the same as using html, but root has higher specificity than html. For example;
:root{ background: #01f001; padding: 0; }
It is more useful when we want to declare a global CSS variables, Example:
:root{ --main-color: green; --pane-padding: 10px 15px; }
:target We use this to select and style links that end with URL fragments with an id. The URL fragment is denoted by a #. For example: See example below.
Note: In the example below, style will be applied when the page is accessed using the URL fragment.
:valid We use this type of pseudo-class selectors to highlight and style form field elements that validate. That is, the correct input is entered in them. It is basically used to highlight successes. See example below.
:visited We use this to select and style the <a> elements that has been visited. For example:
Pseudo-Elements Selector
Pseudo-elements selector is like pseudo-class selectors but they are preceded by double colon “::”. They are used to select and style a particular part of an element, but not the entire element. They include:
::after, ::before, ::first-letter, ::first-line, ::selection, and ::backdrop.
::after – This pseudo-element selector is used to add a last child to the selected element. It is used alongside content and appears inline when rendered. See example below.
::before – Is like the ::after, but is used to create a first child for the element. See example.
::first-letter – We usually use this pseudo-element selector to create a drop cap effect in a paragraph text. It isolates and styles the first letter of the first line in a block. See example below.
::first-line – We use this to select and style the first line of a given text block. See example below.
::selection – This is used to select and apply a style to a group of texts highlighted by a user. See example below. In the example, select a group of text and see the effect.
::backdrop – Is used to select and apply CSS to elements in fullscreen mode.
The embedded code has the examples of all the pseudo elements selector discussed here. The CSS is explicitly commented to distinguish all the examples.