Hertha  Mayer

Hertha Mayer

1621482091

How to Use CSS Selectors to Style Your Web Page

CSS selectors are one of the most important parts of CSS. They give you the ability to target HTML elements on your web page that you want to style.

Originally published by Peter Lynch at https://www.freecodecamp.org/

Without CSS selectors, you wouldn’t be able to style your page to look how you want.

Thankfully CSS selectors have been around for a while, and you can style elements on your however you want.

But if you to really want to unlock the power of CSS and create amazing elements, then you need to understand what you can do with CSS selectors. Namely, you need to understand the basic CSS selectors before you work your way up to the advanced CSS selectors.

This post will look into both. By the end, it will have you well on your way to unlocking the power of CSS selectors to create your own incredible elements. So let’s get started by looking at what CSS selectors are.

What are CSS Selectors?

If you’ve written any CSS before, then you’ve likely seen a CSS selector. They are the first part of a CSS rule. You use CSS selectors to select the HTML elements you want to style.

In CSS, selectors are defined by the CSS selector specification. This means that each selector must be supported by the browser for it to actually work.

CSS selectors tend to be split into five different categories. This post is going to look at them in two key categories of basic and advanced. Below are the five categories.

  1. Simple selectors
  2. Combinator selectors
  3. Pseudo-class selectors
  4. Pseudo-element selectors
  5. Attribute selectors

In order to get good at something you have to understand the basics so let’s start there.

Basic CSS Selectors

You’ve likely seen many types of CSS selectors – the fundamental CSS selectors that are enough to get you building stylish web pages. Let’s look at each of the basic CSS selectors to ensure we understand what they do.

CSS Element (type) selector

The CSS element selector selects HTML elements based on the element name. In HTML element names are things like h1p, or semantic names like article or footer. Therefore, element selectors select all the HTML elements with the name you select.

Let’s look a CSS selector example for element selectors:

/* selecting all h3 elements */
h3 {
	text-align: center;
	color: blue;
}

/* selecting all article elements */
article {
	font-size: 14px;
	line-height: 1.1px;
}

In the example above, we have selected all elements on the page that are of the type h3 and article and applied styles to those elements.

Element selectors help you keep your code simple by applying the styling to all elements on a page of that type. This means you only have to keep track of your styles for those elements in one place.

CSS id selector

The id selector selects the HTML elements that have an id attribute that matches the selector. As you cannot have more than one element with the same id in a HTML document, this selector allows you to select an individual element. This means that the styling on the selected element will be unique.

To select an element with a specific id, you use a # (hash) character followed by the id of the HTML element. In this case it would look something like this #id-name.

Let’s look a CSS selector example for the id selector.

#projects-flex-container {
	width: 90vw;
	display: flex;
}

In the example above, we have selected the individual HTML element with the id #projects-flex-container and applied styling to it. This styling will only apply to that individual element.

One thing to note, though, is that you should be careful when using id selectors. As id selectors can’t be reused on other elements, you should be asking yourself if you need to be using an id selector to target the element.

CSS class selector

The class selector selects HTML elements that have a class attribute that matches the selector. The class selector is useful for targeting multiple elements, things like cards or images that you want to have matching styles.

To select an element with a specific class, you use a . character (period) and then follow it with the class name.

Let’s look a CSS selector example for the class selector.

.project-card {
	color: #badA55;
	padding: 5px;
	border-radius: 5px;
}

In the above example we have selected all elements with the class name project-card using the CSS class selector. All elements with the class project-card will have the styles listed applied to them.

Universal selector

The universal selector selects all HTML elements. This means every single element on your page, from the headings to the footer. You’ll often use it to make the page’s margin and padding consistent or to do what is know as zero out.

The syntax for the universal selector is the * character (star).

* {
	margin: 0;
	padding: 0;
}

In the above example, it has zeroed out the margin and padding for the whole page by using the universal selector.

How to Group CSS Selectors

Before we get into the advanced CSS selectors, we need to quickly look at grouping CSS selectors. This is a common practice you will see out in the wild and it helps make your code clean and readable.

Grouping allows you to select multiple HTML elements at once and only state their style definitions once.

Let’s look at an example of a grouping selector to explain.

h1 {
	text-align: left;
	letter-spacing: 3px;
	color: #111111;
}

h2 {
	text-align: left;
	letter-spacing: 3px;
	color: #111111;
}

h3 {
	text-align: left;
	letter-spacing: 3px;
	color: #111111;
}

In the above CSS code we have three elements h1h2 and h3 and each of these elements have the same style definitions. As a result we can clean up our code by grouping the selectors.

To group selectors we separate each selector with a , character (comma).

h1, h2, h3 {
	text-align: left;
	letter-spacing: 3px;
	color: #111111;
}

Because their style definitions are the same, we now only have to write it once.

Note that grouping selectors can be used for all of the selectors mentioned in this article, meaning the selectors don’t have to match.

We could group a class selector with an id selector if we want them to share style definitions. And we could group the style property and values that match and then define different definitions on each element.

Let’s extend our example to understand this concept.

/*group the selectors and state definitions that are the same*/

h1, h2, h3 {
	text-align: left;
	letter-spacing: 3px;
	color: #111111;
}

/*apply individual styles to selectors*/

h1 {
	font-size: 72px;
}

h2 {
	font-size: 48px;
}

h3 {
	font-size: 32px;
}

There you have it, these are all the basic CSS selectors. If you want to get good at CSS you need to understand what each of these do. With that knowledge in had, you should now be well on your way to doing that.

If you want to level up your CSS, then you will want to understand advanced CSS selectors.

Advanced CSS Selectors

Advanced CSS selectors allow you to push the boundaries of CSS. They help you get highly specific in what elements you want to target and what state that element is in when targeting it.

Let’s get straight into some advanced CSS selectors by looking at attribute selectors.

CSS attribute selectors

Attribute selectors let you select elements based on whether a certain attribute is present or not. To put it another way, this CSS selector will match any element on your page if it has a certain attribute.

An attribute is content added to the opening tag of a HTML element. It can be things like idname or value.

<a title="Learn to code for free!" href="https://www.freecodecamp.org/">Learn to code</a>

The title is an attribute of the a element.

There are seven attribute selectors that each allow you to find elements based on whether an attribute is present and what the value may contain.

  1. Present selector
  2. Equals selector (=)
  3. Begins with selector (^)
  4. Ends with selector ($)
  5. Contains selector (*)
  6. White space selector (~)
  7. Hypen selector (|)

The common syntax for these selectors is the selector followed by [ ] (square brackets) in which you state what you are looking for. The selector could be anything like a class selector or even a universal selector.

selector[attribute] 

Today we are going to look at the five most common attribute selectors. In order to understand these five attribute selectors, let’s look at each of them with examples.

Present attribute selector

This attribute selector finds any element based on where it includes an attribute.

Let’s look at an example of a present selector to explain.

a[title] {
	color: khaki;
	background: grey; 
}

In the example above, our present selector will find any a element that has a title attribute and apply the style definition to them. All other a elements that don’t have a title attribute will not be styled as per above.

Equals attribute selector

This attribute selector finds an element with an exact match attribute value. To use this selector, you state the attribute name followed by an = (equals) to find the exact match of the value.

Let’s look at an example of an equals selector to explain.

a[href="<https://peterlunch.com/>"] {
	color: purple;
} 

In the example above, the equals selector will find any a element that has an href attribute with the exact value of “https://peterlunch.com/”.

Begins with attribute selector

This attribute selector finds any element that begins with a value you specify. To use this selector you state the attribute you are looking for, followed by the ^ and = characters and then the value you are looking to match.

Let’s look at an example of a begins with selector to explain.

a[href^="https"] {
	color: yellow;
	text-decoration: none;
}

In the example above the begins with selector finds any a element that has an href attribute and that begins with “https”.

Ends with attribute selector

Much like the begin with selector, this attribute selector does the opposite and finds any element that ends with a value you specify.

To use this selector you state the attribute you are looking for, followed by the $ and = characters and then the value you are looking to match.

Let’s look at an example of an ends with selector to explain.

img[src$="/blog-imgs"] {
	border-radius: 4px;
	box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

In the above example the ends with selector finds any img element that has an src ending with “/blog-imgs”. This is one I actually use for my website.

Contains attribute selector

This attribute selector finds any element that contains the value you are looking for somewhere in the attributes value. This means that the value must contain at least one occurrence of the value.

To use this selector you state the attribute you are looking for, followed by the * and = characters and then the value you are looking for an occurrence of.

Let’s look at an example of a contains selector to explain.

a[href*="peterlunch"] {
	color: green;
}

In the above example the contains attribute selector finds any a element that has an href that contains the value “peterlunch”.

That’s it for attribute selectors, let’s move onto the next advanced CSS selector.

Combination selectors

The next advanced CSS selectors are combination selectors. These selectors can combine more than one CSS selector. There are four types of combination selectors in CSS:

  1. Descendant selectors
  2. Child selectors
  3. Adjacent sibling selectors
  4. General sibling selectors

To understand how these selectors work, you must first understand that HTML follows a family tree hierarchy. This means that there is a parent element which can contain children, and the children can have children, and so on and so forth like a family tree.

<div> <!--parent-->
	<p> <!--div child-->
	<article> <!--div child, parent to h1 & p-->	 
		<h1>
			<p></p>
		</h1>
	</article>
	<article>	
		<h1>
			<p></p>
			<p></p>
		</h1>
	</article>
</div>

In the example above, the div is the parent, its children are the article elements, and the articles are parents to the h1 and p children.

With that knowledge front of mind, let’s explore each of these combination selectors one by one with examples to understand how they work.

Descendant combination selector

The descendant combination selector matches all elements that are descendants of a specified element.

Let’s look at an example of a descendant combination to explain.

div p {
	line-height: 2em;
}

The above example selects all p elements inside of div elements.

Child combination selector

The child combination selector matches all elements that are children of a specific element. This is different to the descendant combination selector, as it only selects direct children of the parent element.

Child selectors are denoted with a > character.

Let’s look at an example of a child combination selector to explain.

div > p {
	color: aquamarine;
}

Referring to our HTML hierarchy example above, this selector will only find the first p tag and not the p tags within the article tags. It does this as they are not direct children of the parent div element.

Adjacent sibling combination selector

Adjacent Sibling selectors are denoted using a + which separates two selectors and matches the second selector element only if it immediately follows the first element.

A good real world example of this is having the text that immediately follows an image to be styled like a caption.

img + p {
	font-size: 10px;
	color: grey;
	font-style: italic;
}

In the example above, any p element that follows an image will be styled with the above definition.

General sibling combination selector

The general sibling selector selects any elements that are siblings of an element. General sibling selectors are denoted with a ~ character.

Let’s look at an example of a general sibling selector to explain.

article ~ h1 {
	font-weight: 900;
}

In the example above it selects all h1 elements that are siblings of article elements.

Pseudo-selectors

Pseudo-selectors fall into two buckets. The first is pseudo-class selectors and the second is pseudo-element selectors.

These selectors are complex and have a lot of options. To understand them it is worth reading some separate posts on them as they are complex topics on their own. But, I’ll briefly touch on both here.

Firstly pseudo-class selectors select elements based on a certain state. You might have seen things like :hover or :active. These are the states of elements on your page. You can select elements based on whether that element is in the specified state.

A quick example would be:

button:hover {
	background: red;
}

In the example above, when a user hovers over a button the background color will change to red.

If you want to better understand pseudo-class selectors I encourage you to read this post by Nash Vail, who does a fantastic job of explaining them.

Next are pseudo-element selectors which I have written about here. These selectors select parts of an element. A part of an element might be the first letter of the element or the content before and after the element.

With pseudo-element selectors it is important to note that they use :: (double colons) vs. : (single colons) like pseudo classes.

p {
  width: 600px;
  line-height: 1.5;
  font-weight: 500;
}

p::first-letter {
  color: white;
  background-color: rgb(55, 97, 117);
  border-radius: 3px;
  box-shadow: 3px 3px 0 rgb(212, 173, 81);
  font-size: 250%;
  padding: 6px 3px;
  margin-right: 6px;
  float: left;
}

Summary

Now you should have a good understanding of CSS selectors and how you can use them to find HTML elements on your web pages.

I hope you enjoyed reading this article. If you learnt something from this post then checkout the rest of my posts here or sign up to my newsletter to get ridiculously good and super exclusive newbie content.

#css #web-development #programming #developer

What is GEEK

Buddha Community

How to Use CSS Selectors to Style Your Web Page
Alisha  Larkin

Alisha Larkin

1622879640

Top 10 Common CSS Mistakes Web Developers Make

The goal isn't to just write CSS that works. Code CSS that is efficient and easy to maintain

Here are some common mistakes that most web developers make, and how identifying and avoiding them can help you write better and more efficient CSS!

1. Using Color Names Instead of Hexadecimal

2. Hard Coding px Instead of Relative Units

3. Not Using Font Fallbacks

4. Not Using CSS Shorthands

5. Over Qualifying Selectors

6. Using ID’s instead of Classes

7. Not Using CSS Reset

8. Repetitive Code (Redundant Selectors and Properties)

9. Not Separating Design from Layout

10. Writing Unorganized CSS


1. Using Color Names Instead of Hexadecimal

When you say color: blue; you're essentially telling the computer to display whatever shade of color it thinks blue is. By doing this, you’re giving the browser control over how your web page should be displayed, and as a developer, this is something you should never do. By vaguely naming the color as blue, it can easily differ from the shade of blue that you had in mind, and worse it can also vary from browser to browser.

Using hexadecimal values eg. color: #4169E1; hence becomes something that all developers should adopt. It ensures specificity, is supported by all browsers, and gives back to you the control to decide exactly how you want your web page to be displayed.

Note: An efficient way for finding and using hexadecimal values is by first putting in the name of the closest color to the desired shade, and then inspecting the element to find the hex value using the color dropper.

2. Hard Coding px Instead of Relative Units

While it sometimes becomes imperative to use absolute px values, you should always use relative measurements such as em, % (percent), rem (root-Em), and others whenever possible.

This ensures that the website scales proportionally according to the user’s choice of zoom level and screen/browser size.

So, instead of declaring the sizes in absolutes,

p {
    font-size: 16px;
    line-height: 20px;
    margin-bottom: 8px;
}

do this instead:

p {
    font-size: 1rem;
    line-height: 1.25em;
    margin-bottom: 0.5rem;
}

3. Not Using Font Fallbacks

No matter how beautiful a particular font makes your page look, or how much it catches the eye, you always have to consider that not all font types are supported by all computers. If you’re using a font that some browsers do not support, it means that your web page might not be as beautiful and eye-catching as you’re designing it to be for all users.

So, after you use your favorite font, say Helvetica, always make sure to list fallback fonts that the browser can use in case it isn't supported.

Instead of writing this,

#selector {
  font-family: Helvetica;
}

expand the code by font fallbacks such as:

#selector {
  font-family: Helvetica, Arial, sans-serif;
}

Now, even if the browser doesn't support Helvetica, it would fall back to the second most preferred option Arial before going to the browser default.

4. Not Using CSS Shorthands

Take a look at the CSS below:

font-family: Helvetica;
font-size: 14px;
font-weight: bold;
line-height: 1.5;

This can easily be condensed into a single line using the CSS shorthand for font:

font: bold 14px/1.5 Helvetica;

Similarly, this list of properties for a background image:

background-image: url(background.png);
background-repeat: repeat-y;
background-position: center top;

can be written as:

background: url(background.png) repeat-y center top;

Why are we doing this? The reason is simple. It not only reduces your CSS file size but also makes the stylesheet easier to read and more organized.

Here’s a list of CSS shorthands to help you write cleaner code. It’s all about ingraining it into your coding habits, but once you do it, there's no going back!

5. Over Qualifying Selectors

Just like every other thing in excess, too much specificity is a bad thing. And more often than not, it is not even necessary. Take a look at the CSS below:

header #nav ul li a {...}

First of all, the header specification is absolutely unnecessary since an ID, having the highest specificity, has already been used (IDs are unique and only associated with one element). Moreover, an unordered list (ul) always has list items (li) within. So having to mention that becomes pointless. The same selector can now be written as:

#nav ul a {...}

With CSS there are only two levels of specificity — specific and not specific enough. Including all those extra elements might make it look ‘safe’ but are actually unnecessary and are only adding to the length of your stylesheet.

As a general rule, your selectors should be as short as possible. Be just as specific as is necessary for it to work.

6. Using ID’s instead of Classes

The most cogent argument against using ID’s is that it has a much higher specificity than classes, which is why it becomes hard to overwrite and extend your styles. A class on its own can’t overwrite styles belonging to an ID. To “beat” the ID, you would need either more IDs or to use !important, which can begin specificity wars in your stylesheets.

Class selectors can also be used for several HTML elements on the same page, unlike IDs which are unique to each element. Being able to reuse styles is one of the advantages of CSS.

To maintain a consistent convention, use only the class attributes to define styles and IDs while integrating interactivity with Javascript instead.

7. Not Using CSS Reset

If you have ever displayed an HTML page with no CSS styling, you know that the web browser itself “styles” the page using some default values as a fallback. The text has a particular font size and style, the margin and padding are set to certain values.

While this is a good thing for someone who does not use CSS, it is important to first reset these values when you put your own styles into the page. These values vary from browser to browser, hence a CSS Reset is the only way to ensure that all your styles are uniform and effective.

This entails resetting all the styles of all the HTML elements to a predictable baseline value. Once you do this, you can style all the elements on your page as if they were the same to start with. A blank slate.

An easier but incomplete way to do this is by resetting the margin and padding using a universal selector:

* {margin:0; padding:0;}

For a complete reset, however, you can use the Eric Meyer reset (modifying it as per your choice), to reset borders, underlines, and colors of elements like list items, links, and tables so that you don’t run into unexpected inconsistencies between web browsers.

8. Repetitive Code (Redundant Selectors and Properties)

In general, repeating yourself while coding is not considered a good practice. CSS is no different. Take a look at the code below:

#selector-1 {
  font-style: italic;
  color: #e7e7e7;
  margin: 5px;
  padding: 20px
}
.selector-2 {
  font-style: italic;
  color: #e7e7e7;
  margin: 5px;
  padding: 20px
}

A better way to write this is by combining them, with the selectors separated by a comma (,):

#selector-1, .selector-2 {
  font-style: italic;
  color: #e7e7e7;
  margin: 5px;
  padding: 20px
}

This is not just more efficient, but also reduces maintenance time and page-load speed.

9. Not Separating Design from Layout

The job of CSS is to provide styling, and the job of HTML is to provide structure. Generally, HTML should be written in a way that captures the information hierarchy of the page, ignoring any design concerns. Afterward, CSS can be added to make things ‘look nice.’

However, while HTML provides structure, it cannot always position elements on the exact spot of a page you want it to appear, which is where we use CSS to scaffold the layout of the page. Once an element is put into the right place on the page, it’s easy to style it without worrying about the display and position. This is why Layout CSS should be separated from Design CSS.

Instead of putting the layout as well as design properties together,

.article {
  display: inline-block;
  width: 50%;
  margin-bottom: 1em;
  font-family: sans-serif;
  border-radius: 1rem;
  box-shadow: 12px 12px 2px 1px rgba(0, 0, 0, .2);
}
.sidebar {
  width: 25%;
  margin-left: 5px;
}
<div class="article"></div>
<div class="article sidebar"></div>

Separate the design and layout of elements:

/* layout */
.article, .sidebar {
  display: inline-block;
}
.article {
  width: 50%;
  margin-bottom: 1em;
}
.sidebar {
  width: 25%;
  margin-left: 5px;
}

/* display */
.card {
  font-family: sans-serif;
  border-radius: 1rem;
  box-shadow: 12px 12px 2px 1px rgba(0, 0, 0, .2);
}
<div class="article card"></div>
<div class="sidebar card"></div>

This ensures separation of concerns, which is a common software engineering principle that helps keep our code maintainable and easy to understand.

10. Writing Unorganized CSS

Instead of writing your styles just as you think of them, do yourself a favor and organize your code neatly. This will ensure that next time you come to make a change to your file, you’re still able to navigate it.

  • Comment your CSS: A good tip is to add a block of comments between logical sections in your stylesheet too, to help locate different sections quickly when scanning through, or even give you something to search for to jump right into that part of the CSS. You don’t need to comment every single thing in your CSS, as much of it will be self-explanatory. What you should comment are the things where you made a particular decision for a reason.
  • Create Logical Sections in your Stylesheet: It is a good idea to have all of the common styling first in the stylesheet. This means all of the styles which will generally apply unless you do something special with that element. You will typically have rules set up for body, p, h1, h2, h3, links, and tables. After this, you can have a few utility classes, or properties, things you know you will want to apply to lots of different elements. Finally, include CSS for specific things, broken down by the context, page, or even component in which they are used.

#css #programming #developer 

Alayna  Rippin

Alayna Rippin

1603188000

Creating a CSS Visual Cheatsheet

The other day one of our students asked about possibility of having a CSS cheatsheet to help to decide on the best suited approach when doing this or that layout.

This evolved into the idea of making a visual CSS cheatsheet with all (most) of the common patterns we see everyday and one of the best possible conceptual implementation for them.

In the end any layout could and should be split into parts/blocks and we see every block separately.

Here is our first take on that and we would be happy to keep extending it to help us all.

Please, send you suggestions in the comments in community or via gitlab for the repeated CSS patterns with your favourite implementation for that so that we will all together make this as useful as it can be.

#css #css3 #cascading-style-sheets #web-development #html-css #css-grids #learning-css #html-css-basics

Winning on the Web with Cascading Style Sheets (CSS) Animations

Web animations can be used to attract attention, engage people better, and communicate more clearly and effectively. It can engage and hold people’s attention longer than just a static web page.

#css3 #diving-into-css-animation #creating-animation-with-css #master-css #web-development #programming #web-animation #web-monetization

anita maity

anita maity

1618667723

Sidebar Menu Using Only HTML and CSS | Side Navigation Bar

how to create a Sidebar Menu using HTML and CSS only. Previously I have shared a Responsive Navigation Menu Bar using HTML & CSS only, now it’s time to create a Side Navigation Menu Bar that slides from the left or right side.

Demo

#sidebar menu using html css #side navigation menu html css #css side navigation menu bar #,pure css sidebar menu #side menu bar html css #side menu bar using html css

CSS Specificity: The “What”, The “How”

One of the more confusing (but important) pieces of CSS is specificity. I have to admit, this concept took me quite a while to grasp. And while it is definitely a bit confusing, once you get the hang of it it’s actually fairly straightforward. With that being said, here is a quick “what and how” on understanding CSS specificity.

The “What”

By rule, the browser will read your CSS file from top to bottom. That means if you have two h1 selectors, the one that occurs lower on the file will be read.

h1 {
   color: red
}
h1 {
   color: orange
}
//Browser will display h1’s in orange since it is lower down

Often times when you are writing CSS, you will have multiple “rules” written into your CSS file that may contradict each other. The way the browser determines how to prioritize those rules is through specificity.

Example: Let’s say you have a to-do list. Each to-do has a class of “to-do”, but some of them have a unique ID (using ID’s isn’t recommended, but they are helpful here in understanding specificity):

//HTML

<div class="to-do"> 
    To-Do #1 
</div>
<div class="to-do" id="second-to-do"> 
    To-Do #2 
</div>
<div class="to-do"> 
    To-Do #3 
</div>

In your stylesheet, you style each element with class “to-do” with a background color of red. However, you also style the element with the id of “second-to-do” with a background color of green:

//stylesheet

.to-do{
   background-color: red
}
#second-to-do{
   background-color: green
}

#styling #css #web-page-design #css-specificity #css-in-js