Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply a CSS style to an element?

Tags:

html

css

I am new to CSS and not a programmer. I understand what a class is and I understand what a div is, but what I can't seem to find, is how to set styles on specific elements like the divs of my website.

like image 931
Joost Avatar asked Dec 01 '09 19:12

Joost


People also ask

How do I apply a CSS to a specific element?

The CSS id Selector The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Can I apply a CSS style to an element name?

You can apply a CSS style to the element name by using attribute selectors that match elements based on their attributes.

What is used to apply CSS on a single element?

1 ) Inline CSS is used to apply CSS as a single line of element.


2 Answers

In your HTML

<div class="myClass">Look at me!</div>

In your CSS

.myClass
{
   background-color:#eee;
}

EDIT

As pointed out by Dave, you can assign multiple classes to an element. This means you can modularise you styles as required. Helps with the DRY principle.

For example, in your HTML

<div class="myClass myColor">Look at me too!</div>

In your CSS

.myClass
{
   background-color:#eee;
   color:#1dd;
}

.myColor
{
   color:#111;
}

You should also note, that the order in the class attribute does not matter if different styles have conflicting settings. That is, class="myClass myColor" is exactly the same as class="myColor myClass". Which conflicting setting is actually used is determined by which style is defined last in the CSS.

This means, in the above example, to make the color from myClass be used instead of the color from myColor, you have to change your CSS to switch them around as follows

.myColor
{
   color:#111;
}

.myClass
{
   background-color:#eee;
   color:#1dd;
}
like image 110
Dan McGrath Avatar answered Oct 02 '22 23:10

Dan McGrath


You would create either a class per div or give each div a unique id value.

You would then create a different CSS style for each class or id, which would style the corresponding div element.

#specialDiv {
    font-family: Arial, Helvetica, Sans-Serif;
}

<div id="specialDiv">Content</div>

Or

.specialDiv {
    font-family: Arial, Helvetica, Sans-Serif;
}

<div class="specialDiv">Content</div>

You could also do inline styles for each div element:

<div style="font-family: Arial, Helvetica, Sans-Serif;">Content</div>
like image 21
Justin Niessner Avatar answered Oct 03 '22 00:10

Justin Niessner