CSS Box Model
CSS Box Model
CSS Box Model
Every element that can be displayed is comprised of one or more rectangular boxes. CSS box
model typically describes how these rectangular boxes are laid out on a web page. These boxes
can have different properties and can interact with each other in different ways, but every box
has a content area and optional surrounding padding, border, and margin.
The following diagram demonstrates how the padding, border, and margin CSS properties
determines how much space an element can take on a web page.
Usually when you set the width and height of an element using the CSS width and height
properties, in reality you are only setting the width and height of the content area of an element.
The actual width and height of the element's box depend on several factors.
The actual space that an element's box might take is calculated like this:
Note: In CSS box model; content area of the element's box is the area, where text, images, lists,
tables, forms, videos, etc. appears.
CSS Visibility
The visibility property determines whether an element is visible or hidden.
You can use the visibility property to control whether an element is visible or not. This
property can take one of the following values listed in the table below:
Value Description
visible Default value. The box and its contents are visible.
hidden The box and its content are invisible, but still affect the layout of the page.
This value causes the entire row or column to be removed from the display. This value is used
collapse
for row, row group, column, and column group elements.
Specifies that the value of the visibility property should be inherited from the parent element
inherit
i.e. takes the same visibility value as specified for its parent.
The style rule visibility: collapse; however removes the internal table elements, but it
does not affect the layout of the table in any other way. The space normally occupied by the table
elements will be filled by the subsequent siblings.
Note: If the style rule visibility: collapse; is specified for other elements rather than the
table elements, it causes the same behavior as hidden.
CSS Visibility vs Display
The display and visibility CSS properties appear to be the same thing, but they are in fact quite
different and often confuse those new to web development.
visibility: hidden; hides the element, but it still takes up space in the layout. Child
element of a hidden box will be visible if their visibility is set to visible.
display: none; turns off the display and removes the element completely from the
document. It does not take up any space, even though the HTML for it is still in the source code.
All child elements also have their display turned off, even if their display property is set to
something other than none.
Check out the following demo to find out how display and visibility affect the layouts.
<!DOCTYPE html>
<html>
<head>
<style>
h2.a {
visibility: visible;
h2.b {
visibility: hidden;
</style>
</head>
<body>
</body>
</html>
Output:
Notice that the hidden heading still takes up space on the page.
CSS Pseudo-classes
A CSS pseudo-class selector matches components based on an additional condition and not
necessarily defined by the document tree.
What is Pseudo-class
The CSS pseudo-classes allow you to style the dynamic states of an element such as hover,
active and focus state, as well as elements that are existing in the document tree but can't be
targeted via the use of other selectors without adding any IDs or classes to them, for example,
targeting the first or last child elements.
A pseudo-class starts with a colon (:). Its syntax can be given with:
Anchor Pseudo-classes
These pseudo-classes let you style unvisited links differently from visited ones. The most
common styling technique is to remove underlines from visited links.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
a:link {
color: blue;
a:visited {
text-decoration: none;
</style>
</head>
<body>
</body>
</html>
Some anchor pseudo-classes are dynamic — they're applied as a result of user interaction with
the document like on hover, or on focus etc.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of Dynamic Anchor Pseudo-classes</title>
<style>
a:link {
color: blue;
a:visited {
text-decoration: none;
a:hover {
color: red;
a:active {
color: gray;
a:focus {
color: yellow;
</style>
</head>
<body>
</body>
</html>
These pseudo-classes change how the links are rendered in response to user actions.
:hover applies when a user places cursor over the element, but does not select it.
:active applies when the element is activated or clicked.
:focus applies when the element has keyboard focus.
Note: To make these pseudo-classes work perfectly, you must define them in the exact order —
:link, :visited, :hover, :active, :focus.
The :first-child pseudo-class matches an element that is the first child element of some other
element. The selector ol li:first-child in the example below select the first list item of an
ordered list and removes the top border form it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
ol{
padding: 0;
list-style: none;
ol li{
padding: 10px 0;
li:first-child {
border-top: none;
</style>
</head>
<body>
<ol>
<li>Mix ingredients</li>
</ol>
</body>
</html>
Note: To make :first-child to work in Internet Explorer 8 and earlier versions, a <!DOCTYPE>
must be declared at the top of document.
The :last-child pseudo-class matches an element that is the last child element of some other
element. The selector ul li:last-child in the example below select the last list item from an
unordered list and removes the right border from it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
ul{
padding: 0;
list-style: none;
ul li{
display: inline;
padding: 0 20px;
li:last-child {
border-right: none;
</style>
</head>
<body>
<ul>
<li>Home</li>
<li>About Us</li>
<li>Services</li>
<li>Contact Us</li>
</ul>
</body>
</html>
Note: The CSS :last-child selector does not work in Internet Explorer 8 and earlier versions.
Supports in Internet Explorer 9 and above.
The CSS3 introduces a new :nth-child pseudo-class that allows you to target one or more
specific children of a given parent element. The basic syntax of this selector can be given with
:nth-child(N), where N is an argument, which can be a number, a keyword (even or odd), or
an expression of the form xn+y where x and y are integers (e.g. 1n, 2n, 2n+1, …).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table{
margin: 30px;
border-collapse: collapse;
table tr{
}
table tr th, table tr td{
padding: 10px;
background: #f2f2f2;
</style>
</head>
<body>
<table>
<tr>
<th>Row</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
<td>Carter</td>
<td>johncarter@mail.com</td>
</tr>
<tr>
<td>2</td>
<td>Peter</td>
<td>Parker</td>
<td>peterparker@mail.com</td>
</tr>
<tr>
<td>3</td>
<td>John</td>
<td>Rambo</td>
<td>johnrambo@mail.com</td>
</tr>
<tr>
<td>4</td>
<td>Harry</td>
<td>Potter</td>
<td>harrypotter@mail.com</td>
</tr>
</table>
</body>
</html>
he style rules in the example above simply highlight the alternate table row, without adding any
IDs or classes to the <table> elements.
Tip: The CSS :nth-child(N) selector is very useful in the situations where you have to select
the elements that appears inside the document tree in a specific interval or pattern like at even or
odd places, etc.
CSS Media Types
CSS media types allow you to format your documents to be presented correctly on various types
of media such as screen, print, an aural browser, etc.
One of the most important features of style sheets is that, you can specify separate style sheets
for different media types. This is one of the best ways to build printer friendly Web pages — Just
assign a different style sheet for the "print" media type.
Some CSS properties are only designed for certain media. For example, the page-break-after
property only applies to paged media. However there are several properties that may be shared
by different media types, but may require different values for that property. The font-size
property for example can be used for both screen and print media, but possibly with different
values.
A document usually needs a larger font on a computer screen as compared to the paper for better
readability, also sans-serif fonts are considered easier to read on the screen, while serif fonts are
popular for printing. Therefore it is necessary to specify that a style sheet, or a set of style rules,
applies to certain media types.
Three methods are commonly used to specify the media dependencies for style sheets:
The @media rule is used to define different style rules for different media types in a single style
sheet. It is usually followed by a comma-separated list of media types and the CSS declarations
block containing the styles rules for target media.
The style declaration in the example below tells the browser to display body content in 14 pixels
Arial font on the screen, but in case of printing it will be in a 12 points Times font. However the
value of line-height property is set to 1.2 for both of them:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
@media screen{
body {
color: #32cd32;
font-size: 14px;
@media print {
body {
color: #ff6347;
font-size: 12pt;
body {
line-height: 1.2;
</style>
</head>
<body>
<p><strong>Note:</strong> If you print (or print preview) this page the output of HTML code
appears differently than it appears on the screen.</p>
</body>
</html>
Note: Style rules outside of @media rules apply to all media types that the style sheet applies to.
At-rules inside @media are invalid in CSS2.1.
The @import rule is another way of setting style information for a specific target media — Just
specify the comma-separated media types after the URL of the imported style sheets.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
body {
background: #f6f6f6;
line-height: 1.2;
</style>
</head>
<body>
<p>If you print (or print preview) this page the output of HTML code appears differently
than it appears on the screen. Because different style sheets are used for different media types i.e.
screen.css for computer screen while print.css for print media.</p>
</body>
</html>
The print media type in the @import statement instructs the browser to load an external style
sheet (print.css) and use its styles only for print media.
Note: All @import statements must occur at the beginning of a style sheet, before any
declarations. Any style rule specified in the style sheet itself override the conflicting style rules
in the imported style sheets.
The media attribute on the <link> element is used to specify the target media for an external
style sheet within the HTML document.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<body>
<p>If you print (or print preview) this page the output of HTML code appears differently
than it appears on the screen. Because different style sheets are used for different media types i.e.
screen.css for computer screen while print.css for print media.</p>
</body>
</html>
n this example the media attribute instructs the browser to load an external style sheet
"screen.css" and use its styles only for screen while "print.css" for printing purpose.
Tip: You can also specify multiple media types (each separated with comma e.g.
media="screen, print") as well as media quires to the <link> element.
The following table lists the various media types that may used to target different types of
devices such as printers, handheld devices, computer screens etc.
Used for small or handheld devices — usually small screen devices such as mobile phones
handheld
or PDAs.
Used for media using a fixed-pitch character grid — such as teletypes, terminals, or
tty
portable devices with limited display capabilities.
Used for television-type devices — low resolution, color, limited-scrollability screens,
tv
sound available.
Warning: However there are several media types to choose from but most of the browser only
support all, screen and print media types.
CSS Validation
CSS validation is the process of checking the code against the formal guidelines and standards
set by the Wide Web Consortium (W3C) for CSS document.
As a beginner, it is very common that you will make mistake in writing your CSS code. Incorrect
or non-standard code may cause unexpected results in how your page displayed or functions in a
web browser.
The World Wide Web Consortium (W3C) has created a great tool https://jigsaw.w3.org/css-
validator/ to automatically check your style sheets, and point out any problems/errors your code
might have, such as invalid CSS property missing closing bracket or missing semicolon (;) etc. It
is absolutely free.
Validating a Website
Website validation is the process to ensure that the pages of a website conform to the formal
guidelines and standards set by the World Wide Web Consortium (W3C).
There are several specific reasons for validating a website, some of them are:
It helps to create Web pages that are cross-browser, cross-platform compatible. It also likely to
be compatible with the future version of Web browsers and Web standards.
Standards compliant web pages increase the search engines spider visibility and your pages will
more likely be appear in search results.
It will reduce unexpected errors and make your web pages more accessible to the visitor of your
website.
Note: Validation is important. It will ensure that your web pages are interpreted in the same way
(the way you want it) by the various web browsers, search engines etc. as well as users and
visitors of your Web site.
CSS3 Border
With CSS3, you can apply images to an element's borders.
The CSS3 provides two new properties for styling the borders of an element in a more elegant
way — the border-image property for adding the images to borders, and the border-radius
property for making the rounded corners without using any images.
The following section will describe you these new border properties of CSS3, for other border
related properties please check out the CSS border tutorial.
The border-radius property can be used to create rounded corners. This property typically
defines the shape of the corner of the outer border edge. Prior to CSS3, sliced images are used
for creating the rounded corners that was rather bothersome.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.box {
width: 300px;
height: 150px;
background: #ffb6c1;
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
The border-image property allows you to specify an image to act as an element's border.
The design of the border is created from the sides and corners of the image specified in border-
image source URL. The border image may be sliced, repeated, scaled and stretched in various
ways to fit the size of the border image area.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.box {
width: 300px;
height: 150px;
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
Tip: The round option is a variation of the repeat option that distributes the image tiles in such a
way that the ends are nicely connected.
CSS3 Animations
The CSS3 animations feature allows you to create keyframe animations.
In the previous chapter you've seen how to do simple animations like animating a property from
one value to another via CSS3 transitions feature. However, the CSS3 transitions provide little
control on how the animation progresses over time.
The CSS3 animations take it a step further with keyframe-based animations that allow you to
specify the changes in CSS properties over time as a set of keyframes, like flash animations.
Creating CSS animations is a two step process, as shown in the example below:
The first step of building a CSS animation is to defining individual keyframes and naming an
animation with a keyframes declaration.
The second step is referencing the keyframes by name using the animation-name property as
well as adding animation-duration and other optional animation properties to control the
animation's behavior.
However, it is not necessary to define the keyframes rules before referencing or applying it. The
following example will show you how to animate a <div> box horizontally from one position to
another using the CSS3 animation feature.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.box {
margin: 50px;
width:153px;
height:103px;
position: relative;
-webkit-animation-name: moveit;
-webkit-animation-duration: 2s;
/* Standard syntax */
animation-name: moveit;
animation-duration: 2s;
@-webkit-keyframes moveit {
from {left: 0;}
to {left: 50%;}
/* Standard syntax */
@keyframes moveit {
to {left: 50%;}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
You must specify at least two properties animation-name and the animation-duration
(greater than 0), to make the animation occur. However, all the other animation properties are
optional, as their default values don't prevent an animation from happening.
Note: Not all CSS properties are animatable. In general, any CSS property that accepts values
that are numbers, lengths, percentages, or colors is animatable.
Defining Keyframes
Keyframes are used to specify the values for the animating properties at various stages of the
animation. Keyframes are specified using a specialized CSS at-rule — @keyframes. The
keyframe selector for a keyframe style rule starts with a percentage (%) or the keywords from
(same as 0%) or to (same as 100%). The selector is used to specify where a keyframe is
constructed along the duration of the animation.
Percentages represent a percentage of the animation duration, 0% represents the starting point of
the animation, 100% represents the end point, 50% represents the midpoint and so on. That
means, a 50% keyframe in a 2s animation would be 1s into an animation.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.box {
margin: 50px;
width:120px;
height:110px;
position: relative;
left: 0;
-webkit-animation-name: shakeit;
-webkit-animation-duration: 2s;
/* Standard syntax */
animation-name: shakeit;
animation-duration: 2s;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes shakeit {
/* Standard syntax */
@keyframes shakeit {
</style>
</head>
<body>
<p><strong>Note:</strong> Click the "Show Output" button to repeat the animation.</p>
<div class="box"></div>
</body>
</html>
CSS3 2D Transforms
The CSS3 2D transform feature allows elements to be transformed in 2D space.
2D Transformation of Elements
With CSS3 2D transform feature you can perform basic transform manipulations such as move,
rotate, scale and skew on elements in a two-dimensional space.
A transformed element doesn't affect the surrounding elements, but can overlap them, just like
the absolutely positioned elements. However, the transformed element still takes space in the
layout at its default (un-transformed) location.
The CSS3 transform property uses the transform functions to manipulate the coordinate system
used by an element in order to apply the transformation effect.
Moves the element from its current position to a new position along the X and Y axes. This can
be written as translate(tx, ty). If ty isn't specified, its value is assumed to be zero.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
img {
.box{
margin: 50px;
width:153px;
height:103px;
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>
The rotate() function rotates the element around its origin (as specified by the transform-
origin property) by the specified angle. This can be written as rotate(a).
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
img {
-ms-transform: rotate(30deg); /* IE 9 */
.box{
margin: 50px;
width:120px;
height:110px;
</style>
</head>
<body>
<div class="box">
<img src="/examples/images/star-fish.png" alt="Star Fish">
</div>
</body>
</html>
The scale() function increases or decreases the size of the element. It can be written as
scale(sx, sy). If sy isn't specified, it is assumed to be equal to sx.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
img {
-ms-transform: scale(1.5); /* IE 9 */
opacity: 0.5;
.box{
margin: 50px;
width:103px;
height:130px;
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>
CSS3 3D Transforms
The CSS3 3D transform feature allows elements to be transformed in 3D space.
3D Transformation of Elements
With CSS3 3D transform feature you can perform basic transform manipulations such as move,
rotate, scale and skew on elements in a three-dimensional space.
A transformed element doesn't affect the surrounding elements, but can overlap them, just like
the absolutely positioned elements. However, the transformed element still takes space in the
layout at its default (un-transformed) location.
The CSS3 transform property uses the transform functions to manipulate the coordinate system
used by an element in order to apply the transformation effect.
Moves the element from its current position to a new position along the X, Y and Z-axis. This
can be written as translate(tx, ty, tz). Percentage values are not allowed for third
translation-value parameter (i.e. tz).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.container{
width: 125px;
height: 125px;
perspective: 500px;
background: #fff2dd;
margin: 30px;
.transformed {
</style>
</head>
<body>
<h2>Before Translation:</h2>
<div class="container">
</div>
<h2>After Translation:</h2>
<div class="container">
</div>
</body>
</html>
CSS3 Gradients
The CSS3 gradient feature allows you to create a gradient from one color to another without
using any images.
The CSS3 gradient feature provides a flexible solution to generate smooth transitions between
two or more colors. Earlier, to achieve such effect we had to use the images. Using CSS3
gradients you can reduce the download time and saves the bandwidth usages. The elements with
gradients can be scaled up or down to any extent without losing the quality, also the output will
render much faster because it is generated by the browser.
To create a linear gradient you must define at least two color stops. However to create more
complex gradient effects you can define more color stops. Color stops are the colors you want to
render smooth transitions among. You can also set a starting point and a direction (or an angle)
along which the gradient effect is applied. The basic syntax of creating the linear gradients using
the keywords can be given with:
linear-gradient(direction, color-stop1, color-stop2, ...)
The following example will create a linear gradient from top to bottom. This is default.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.gradient {
width: 400px;
height: 300px;
background: red;
/* Standard syntax */
</style>
</head>
<body>
<div class="gradient"></div>
</body>
</html>
The following example will create a linear gradient from left to right.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.gradient {
width: 400px;
height: 300px;
background: red;
</style>
</head>
<body>
<div class="gradient"></div>
</body>
</html>
You can also create a gradient along the diagonal direction. The following example will create a
linear gradient from the bottom left corner to the top right corner of the element's box.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.gradient {
width: 400px;
height: 300px;
background: red;
/* For Safari 5.1 to 6.0 */
/* Standard syntax */
</style>
</head>
<body>
<div class="gradient"></div>
</body>
</html>