CSS Selectors: What Is Selector?

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

CSS 

Selectors
What is Selector?
A CSS selector is a pattern to match the elements on a web page. The style
rules associated with that selector will be applied to the elements that
match the selector pattern.

Selectors are one of the most important aspects of CSS as they allow you
to target specific elements on your web page in various ways so that they
can be styled.

Several types of selectors are available in CSS, let's take a closer look at
them:

Universal Selector
The universal selector, denoted by an asterisk (*), matches every single
element on the page.

The universal selector may be omitted if other conditions exist on the


element. This selector is often used to remove the default margins and
paddings from the elements for quick testing purpose.

Let's try out the following example to understand how it basically works:
Element Type Selectors
An element type selector matches all instance of the element in the
document with the corresponding element type name. Let's try out an
example to see how it actually works:

Id Selectors
The id selector is used to define style rules for a single or unique element.

The id selector is defined with a hash sign ( #) immediately followed by the


id value.
Class Selectors
The class selectors can be used to select any HTML element that has
a class attribute. All the elements having that class will be formatted
according to the defined rule.

The class selector is defined with a period sign (.) immediately followed by
the class value.

Descendant Selectors
You can use these selectors when you need to select an element that is the
descendant of another element, for example, if you want to target only
those anchors that are contained within an unordered list, rather than
targeting all anchor elements. Let's see how it works:
Child Selectors
A child selector is used to select only those elements that are the direct
children of some element.

A child selector is made up of two or more selectors separated by a greater


than symbol (>). You can use this selector, for instance, to select the first
level of list elements inside a nested list that has more than one level. Let's
check out an example to understand how it works:
Adjacent Sibling Selectors
The adjacent sibling selectors can be used to select sibling elements (i.e.
elements at the same level). This selector has the syntax like: E1 + E2,
where E2 is the target of the selector.

The selector h1 + p in the following example will select the <p> elements


only if both the <h1> and <p> elements share the same parent in the
document tree and <h1> is immediately precedes the <p> element. That
means only those paragraphs that come immediately after
each <h1> heading will have the associated style rules. Let's see how this
selector actually works:

General Sibling Selectors


The general sibling selector is similar to the adjacent sibling selector (E1 +
E2), but it is less strict. A general sibling selector is made up of two simple
selectors separated by the tilde (∼) character. It can be written like: E1 ∼ E2,
where E2 is the target of the selector.

The selector h1 ∼ p in the example below will select all the <p> elements
that preceded by the <h1> element, where all the elements share the same
parent in the document tree.

Grouping Selectors
Often several selectors in a style sheet share the same style rules
declarations. You can group them into a comma-separated list to minimize
the code in your style sheet. It also prevents you from repeating the same
style rules over and over again. Let's take a look:

________________________________________________________________________________

As you can see in the above example, the same style rule font-weight:
normal; is shared by the selectors h1, h2 and h3, so it can be grouped in a
comma-separated list, like this:
CSS Color
In this tutorial you will learn the different methods of defining color values
in CSS.

Setting Color Property


The color property defines the text color (foreground color in general) of an
element.

For instance, the color property specified in the body selector defines the


default text color for the whole page. Let's try out the following example to
see how it works:

Example
Try this code »
body {
color: #ff5722;
}

Note: The color property normally inherits the color value from their parent


element, except the case of anchor elements. For example, if you
specify color for the body element it will automatically be passed down to
the headings, paragraphs, etc.

Defining Color Values


Colors in CSS most often specified in the following formats:

 a color name - like "red"


 a HEX value - like "#ff0000"
 an RGB value - like "rgb(255, 0, 0)"
CSS3 has introduced several other color formats such as HSL, HSLA and
RGBA that also support alpha transparency. We'll learn about them in
greater detail in CSS3 color chapter.

For now, let's stick to the basic methods of defining the color values:

Color Keywords
CSS defines the few color keywords which lets you specify color values in
an easy way.

These basic color keywords are: aqua, black, blue, fuchsia, gray, green, lime,
maroon, navy, olive, purple, red, silver, teal, white, and yellow. The color
names are case-insensitive.

Example
Try this code »
h1 {
color: red;
}
p {
color: purple;
}

Modern web browsers however practically support many more color names
than what are defined in the CSS standard, but to be on the safer side you
should use hex color values instead.

See the reference on CSS color names, for a complete list of possible color
names.

HEX Color Values


Hex (short for Hexadecimal) is by far the most commonly used method of
defining color on the web.
Hex represent colors using a six-digit code, preceded by a hash character,
like #rrggbb, in which rr, gg, and bb represents the red, green and blue
component of the color respectively.

The value of each component can vary from 00 (no color) and FF (full color)
in hexadecimal notation, or 0 and 255 in decimal equivalent notation.
Thus #ffffff represents white color and #000000 represents black color. Let's
take a look the following example:

Example
Try this code »
h1 {
color: #ffa500;
}
p {
color: #00ff00;
}

Note: Hexadecimal or Hex refers to a numbering scheme that uses 16


characters as its base. It uses the numbers 0 through 9 and the letters A, B,
C, D, E and F which corresponds to the decimal numbers 10, 11, 12, 13, 14
and 15 respectively.

Tip: If hexadecimal code of a color has value pairs, it can also be written in
shorthand notation to avoid extra typing, for example, the hex color value
#ffffff can be also be written as #fff, #000000 as #000, #00ff00 as #0f0,
#ffcc00 as #fc0, and so on.

RGB Color Values


Colors can be defined in the RGB model (Red, Green, and Blue) using
the rgb() functional notation.

The rgb() function accepts three comma-separated values, which specify


the amount of red, green, and blue component of the color. These values
are commonly specified as integers between 0 to 255, where 0
represent no color and 255 represent full or maximum color.
The following example specifies the same color as in the previous example
but in RGB notation.

Example
Try this code »
h1 {
color: rgb(255, 165, 0);
}
p {
color: rgb(0, 255, 0);
}

Note: You can also specify RGB values inside the rgb() function in


percentage, where 100% represents full color, and 0% (not simply 0)
represents no color. For example, you can specify the red color either
as rgb(255, 0, 0) or rgb(100%, 0%, 0%).

Tip: If R, G, and B are all set to 255, i.e. rgb(255, 255, 255), the color would
be white. Likewise, if all channels are set to 0, i.e. rgb(0, 0, 0), the color
would be black. Play with the RGB values in the following demonstration to
understand how it actually works.

Setting Background Properties


Background plays an important role in the visual presentation of a web
page.

CSS provide several properties for styling the background of an element,


including coloring the background, placing images in the background and
managing their positioning, etc.

The background properties are background-color, background-image, background-


repeat, background-attachment and background-position.

In the following section we will discuss each of these properties in more


detail.

Background Color
The background-color property is used to set the background color of an
element.
The following example demonstrates how to set the background color of
the whole page.

Example
Try this code »
body {
background-color: #f0e68c;
}

Color values in CSS are most often specified in the following formats:

 a color name - like "red"


 a HEX value - like "#ff0000"
 an RGB value - like "rgb(255, 0, 0)"

Please check out the tutorial on CSS color to learn more about specifying
color values.

Background Image
The background-image property set an image as a background of an HTML
element.

Let's check out the following example which sets the background image for
the whole page.

Example
Try this code »
body {
background-image: url("images/tile.png");
}

Note: When applying the background image to an element, make sure


that the image you choose does not affect the readability of the element's
text content.
Tip: By default browser repeats or tiles the background image both
horizontally and vertically to fill the entire area of an element. You can
control this with background-repeat property.

Background Repeat
The background-repeat property allows you to control how a background
image is repeated or tiled in the background of an element. You can set a
background image to repeat vertically (y-axis), horizontally (x-axis), in both
directions, or in neither direction.

Let's try out the following example which demonstrates how to set the
gradient background for a web page by repeating the sliced image
horizontally along the x-axis.

Example
Try this code »
body {
background-image: url("images/gradient.png");
background-repeat: repeat-x;
}

Similarly, you can use the value repeat-y to repeat the background image
vertically along the y-axis, or the value no-repeat to prevent the repetition
altogether.

Example
Try this code »
body {
background-image: url("images/texture.png");
background-repeat: no-repeat;
}

Let's take a look at the following illustration to understand how this


property actually works.
Background Position
The background-position property is used to control the position of the
background image.

If no background position has been specified, the background image is


placed at the default top-left position of the element i.e. at (0,0), let's try
out the following example:

Example
Try this code »
body {
background-image: url("images/robot.png");
background-repeat: no-repeat;
}

In the following example, the background image is positioned at top-right


corner.

Example
Try this code »
body {
background-image: url("images/robot.png");
background-repeat: no-repeat;
background-position: right top;
}

Note: If two values are specified for the background-position property, the


first value represents the horizontal position, and the second represents
the vertical position. If only one value is specified, the second value is
assumed to be center.

Besides keywords, you can also use percentage or length values, such
as px or em for this property.

Let's take a look at the following illustration to understand how this


property actually works.
Background Attachment
The background-attachment property determines whether the background
image is fixed with regard to the viewport or scrolls along with the
containing block.

Let's try out the following example to understand how it basically works:

Example
Try this code »
body {
background-image: url("images/bell.png");
background-repeat: no-repeat;
background-attachment: fixed;
}

The Background Shorthand Property


As you can see in the examples above, there are many properties to
consider when dealing with the backgrounds. However, it is also possible
to specify all these properties in one single property to shorten the code or
avoid extra typing. This is called a shorthand property.

The background property is a shorthand property for setting all the individual


background properties, i.e., background-color, background-image, background-
repeat, background-attachment and the background-position property at once.
Let's see how this works:

Example
Try this code »
body {
background-color: #f0e68c;
background-image: url("images/smiley.png");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 250px 25px;
}

Using the shorthand notation the above example can be written as:

Example
Try this code »
body {
background: #f0e68c url("images/smiley.png") no-repeat
fixed 250px 25px;
}

When using the background shorthand property the order of the property


values should be.

background: color image repeat attachment position;

If the value for an individual background property is missing or not


specified while using the shorthand notation, the default value for that
property will be used instead, if any.

Note: The background properties do not inherit like the color property, but


the parent element's background will be visible through by default,
because of the initial or default transparent value of the background-color CSS
property.

CSS Fonts
In this tutorial you will learn how to style fonts on a web page using CSS.

Styling Fonts with CSS


Choosing the right font and style is very crucial for the readability of text
on a page.

CSS provide several properties for styling the font of the text, including
changing their face, controlling their size and boldness, managing variant,
and so on.
The font properties are: font-family, font-style, font-weight, font-size,
and font-variant.

Let's discuss each of these font properties one by one in more detail.

Font Family
The font-family property is used to specify the font to be used to render
the text.

This property can hold several comma-separated font names as


a fallback system, so that if the first font is not available on the user's
system, browser tries to use the second one, and so on.

Hence, list the font that you want first, then any fonts that might fill in for
the first if it is not available. You should end the list with a generic font
family which are five — serif, sans-serif, monospace, cursive and fantasy. A
typical font family declaration might look like this:

Example
Try this code »
body {
font-family: Arial, Helvetica, sans-serif;
}

Note: If the name of a font family contains more than one word, it must be
placed inside quotation marks, like "Times New Roman", "Courier New", "Segoe
UI", etc.

The most common font families used in web design are serif and sans-serif,


because they are more suitable for reading. While monospace fonts are
commonly used to display code, because in this typeface each letter takes
up the same space which looks like typewritten text.

The cursive fonts look like cursive writing or handwriting. The fantasy font


represents artistic font, but they're not used widely because of poor
availability across the operating systems.

Difference Between Serif and Sans-serif Fonts


Serif fonts have small line or stroke at the extremities of characters,
whereas sans-serif fonts are straighter and do not have these small strokes.
See the following illustration.

To learn about commonly used font combinations, please check out the
reference on web safe fonts.

Font Style
The font-style property is used to set the font face style for the text content
of an element.

The font style can be normal, italic or oblique. The default value is normal.

Let's try out the following example to understand how it basically works:

Example
Try this code »
p.normal {
font-style: normal;
}
p.italic {
font-style: italic;
}
p.oblique {
font-style: oblique;
}

Note: At first glance both oblique and italic font styles appear the same
thing, but there is a difference. The italic style uses an italic version of the
font while oblique style on the other hand is simply a slanted or sloped
version of the normal font.

Font Size
The font-size property is used to set the size of font for the text content of
an element.

There are several ways to specify the font size values e.g. with keywords,
percentage, pixels, ems, etc.

Setting Font Size with Pixels


Setting the font size in pixel values (e.g. 14px, 16px, etc.) is a good choice
when you need the pixel accuracy. Pixel is an absolute unit of measurement
which specifies a fixed length.

Let's try out the following example to understand how it basically works:

Example
Try this code »
h1 {
font-size: 24px;
}
p {
font-size: 14px;
}

Defining the font sizes in pixel is not considered very accessible, because
the user cannot change the font size from the browser settings. For
instance, users with limited or low vision may wish to set the font size
much larger than the size specified by you.

Therefore, you should avoid using the pixels values and use the values that
are relative to the user's default font size instead if you want to create an
inclusive design.
Tip: The text can also be resized in all browsers using the zoom feature.
However, this feature resizes the entire page, not just the text.
The W3C recommends using the em or percentage (%) values in order to
create more robust and scalable layouts.

Setting Font Size with EM


The em unit refers to the font size of the parent element. When defining
the font-size property, 1em is equal to the size of the font that applies to
the parent of the element.

So, if you set a font-size of 20px on the body element, then 1em = 


20px and 2em = 40px.

However, if you haven't set the font size anywhere on the page, then it is
the browser default, which is normally 16px. Therefore, by default 1em = 
16px, and 2em = 32px.

Let's take a look at the following example to understand how it basically


works:

Example
Try this code »
h1 {
font-size: 2em; /* 32px/16px=2em */
}
p {
font-size: 0.875em; /* 14px/16px=0.875em */
}

Using the Combination of Percentage and EM


As you've observed in the above example the calculation of em values
doesn't look straightforward. To simplify this, a popular technique is to set
the font-size for the body element to 62.5% (that is 62.5% of the default
16px), which equates to 10px, or 0.625em.

Now you can set the font-size for any elements using em units, with an
easy-to-remember conversion, by dividing the px value by 10. This
way 10px = 1em, 12px = 1.2em, 14px = 1.4em, 16px = 1.6em, and so on. Let's take a
look at the following example:
Example
Try this code »
body {
font-size: 62.5%; /* font-size 1em = 10px */
}
p {
font-size: 1.4em; /* 1.4em = 14px */
}
p span {
font-size: 2em; /* 2em = 28px */
}

Setting Font Size with Root EM


To make things even more simpler CSS3 has introduced rem unit (short for
"root em") which is always relative to the font-size of the root element
(html), regardless of where the element lies in the document
(unlike em which is relative to parent element's font size).

This means that 1rem is equivalent to the font size of the html element,


which is 16px by default in most browsers. Let's try out an example to
understand how it actually works:

Example
Try this code »
html {
font-size: 62.5%; /* font-size 1em = 10px */
}
p {
font-size: 1.4rem; /* 1.4rem = 14px */
}
p span {
font-size: 2rem; /* 2rem = 20px (not 28px) */
}

Setting Font Size with Keywords


CSS provide several keywords that you can use to define font sizes.

An absolute font size can be specified using one of the following


keywords: xx-small, x-small, small, medium, large, x-large, xx-large. Whereas, a
relative font size can be specified using the keywords: smaller or larger.
Let's try out an example and see how it works:

Example
Try this code »
body {
font-size: large;
}
h1 {
font-size: larger;
}
p {
font-size: smaller;
}

Note: The keyword medium is equivalent to the browsers default font-size,


which is normally 16px. Likewise, xx-small is the equivalent of 9 pixels, x-
small is 10 pixels, small is 13 pixels, large is 18 pixels, x-large is 24 pixels,
and xx-large is 32 pixels.

Tip: By setting a font size on the body element, you can set the relative
font sizing everywhere else on the page, giving you the ability to easily
scale the font size up or down accordingly.

Setting Font Size with Viewport Units


The font sizes can be specified using viewport units such as vw or vh.

Viewport units refer to a percentage of the browser's viewport dimensions,


where 1vw = 1% of viewport width, and 1vh = 1% of viewport height.
Hence, if the viewport is 1600px wide, 1vw is 16px.

Try out the following example by resizing the browser window and see how
it works:

Example
Try this code »
body {
font-size: 1vw;
}
h1 {
font-size: 3vw;
}

However, there is a problem with the viewport units. On small screens fonts
become so small that they are hardly readable. To prevent this you can
utilize CSS calc() function, like this:

Example
Try this code »
html {
font-size: calc(1em + 1vw);
}
h1 {
font-size: 3rem;
}

In this example, even if the viewport width becomes 0, the font-size would
be at least 1em or 16px.

You further utilize CSS media queries to create better responsive and fluid
typography.

Font Weight
The font-weight property specifies the weight or boldness of the font.

This property can take one of the following


values: normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900 and i
nherit.

 The numeric values 100-900 specify the font weights, where each


number represents a weight greater than its predecessor. 400 is same
as normal & 700 is same as bold.
 The bolder and lighter values are relative to the inherited font weight,
while the other values such as normal and bold are absolute font weights.

Let's try out an example to understand how this property basically works:
Example
Try this code »
p {
font-weight: bold;
}

Note: Most of the fonts are only available in a limited number of weights;


often they are available only in normal and bold. In case, if a font is not
available in the specified weight, an alternate will be chosen that is the
closest available weight.

Font Variant
The font-variant property allows the text to be displayed in a special small-
caps variation.

Small-caps or small capital letters are slightly different to normal capital


letters, in which lowercase letters appear as smaller versions of the
corresponding uppercase letters.

Try out the following example to understand how this property actually
works:

Example
Try this code »
p {
font-variant: small-caps;
}

The value normal removes small caps from the text which is already


formatted that way

CSS Text
Formatting Text with CSS
CSS provides several properties that allows you to define various text styles
such as color, alignment, spacing, decoration, transformation, etc. very
easily and effectively.

The commonly used text properties are: text-align, text-decoration, text-


transform, text-indent, line-height, letter-spacing, word-spacing, and more.
These properties give you precise control over the visual appearance of
the characters, words, spaces, and so on.

Let's see how to set these text properties for an element in more detail.

Text Color
The color of the text is defined by the CSS color property.

The style rule in the following example will define the default text color for
the page

Example
Try this code »
body {
color: #434343;
}

Although, the color property seems like it would be a part of the CSS text,
but it is actually a standalone property in CSS. See the tutorial on CSS
color to learn more about the color property.

Text Alignment
The text-align property is used to set the horizontal alignment of the text.

Text can be aligned in four ways: to the left, right, centre or justified
(straight left and right margins).

Let's take a look at an example to understand how this property basically


works.
Example
Try this code »
h1 {
text-align: center;
}
p {
text-align: justify;
}

Note: When text-align is set to justify, each line is stretched so that every


line has equal width (except the last line), and the left and right margins are
straight. This alignment is generally used in publications such as magazines
and newspapers.

Let's take a look at the following illustration to understand what these


values actually mean.

Text Decoration
The text-decoration property is used to set or remove decorations from text.

This property typically accepts one of the following


values: underline, overline, line-through, and none. You should avoid underline
text that is not a link, as it might confuse the visitor.

Let's try out the following example to understand how it basically works:
Example
Try this code »
h1 {
text-decoration: overline;
}
h2 {
text-decoration: line-through;
}
h3 {
text-decoration: underline;
}

Removing the Default Underline from Links


The text-decoration property is extensively used to remove the default
underline from the HTML hyperlinks. You can further provide some other
visual cues to make it stand out from the normal text, for example, using
dotted border instead of solid underline.

Let's take a look at the following example to understand how it basically


works:

Example
Try this code »
a {
text-decoration: none;
border-bottom: 1px dotted;
}

Note: When you create an HTML link, browsers built in style sheet


automatically underline it and applies a blue color, so that the readers can
clearly see which text is clickable.

Text Transformation
The text-transform property is used to set the cases for a text.
Text are often written in mixed case. However, in certain situations you may
want to display your text in entirely different case. Using this property you
can change an element's text content into uppercase or lowercase letters,
or capitalize the first letter of each word without modifying the original
text.

Let's try out the following example to understand how it basically works:

Example
Try this code »
h1 {
text-transform: uppercase;
}
h2 {
text-transform: capitalize;
}
h3 {
text-transform: lowercase;
}

Text Indentation
The text-indent property is used to set the indentation of the first line of
text within a block of text. It is typically done by inserting the empty space
before the first line of text.

The size of the indentation can be specified using percentage (%), length
values in pixels, ems, etc.

The following style rule will indent the first line of the paragraphs by 100
pixels.

Example
Try this code »
p {
text-indent: 100px;
}
Note: Whether the text is indented from the left or from the right depends
on the direction of text inside the element, defined by the
CSS direction property.

Letter Spacing
The letter-spacing property is used to set extra spacing between the
characters of text.

This property can take a length value in pixels, ems, etc. It may also accept
negative values. When setting letter spacing, a length value indicates
spacing in addition to the default inter-character space.

Let's check out the following example to understand how it really works:

Example
Try this code »
h1 {
letter-spacing: -3px;
}
p {
letter-spacing: 10px;
}

Word Spacing
The word-spacing property is used to specify additional spacing between the
words.

This property can accept a length value in pixels, ems, etc. Negative values
are also allowed.

Let's try out the following example to understand how this property works:
Example
Try this code »
p.normal {
word-spacing: 20px;
}
p.justified {
word-spacing: 20px;
text-align: justify;
}
p.preformatted {
word-spacing: 20px;
white-space: pre;
}

Note: Word spacing can be affected by text justification. Also, even though


whitespace is preserved, spaces between words are affected by the word-
spacing property.

Line Height
The line-height property is used to set the height of the text line.

It is also called leading and commonly used to set the distance between


lines of text.

The value of this property can be a number, a percentage (%), or a length


in pixels, ems, etc.

Example
Try this code »
p {
line-height: 1.2;
}

When the value is a number, the line height is calculated by multiplying the
element's font size by the number. While, percentage values are relative to
the element's font size.
Note: Negative values for the line-height property are not allowed. This
property is also a component of the CSS font shorthand property.

If the value of the line-height property is greater than the value of the font-


size for an element, this difference (called the "leading") is cut in half (called
the "half-leading") and distributed evenly on the top and bottom of the in-
line box. Let's check out an example:

Example
Try this code »
p {
font-size: 14px;
line-height: 20px;
background-color: #f0e68c;
}

See the tutorial on CSS3 text overflow in the advanced section to learn how
to handle overflowed text. Also see the CSS3 text shadow section to learn
how to apply shadow effect on text.

You might also like