How do I apply a CSS style to an element?
I am new to CSS and not a programmer. I unde开发者_StackOverflow中文版rstand 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.
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;
}
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>
<div class="featured">Featured</div>
<style type="text/css">
.featured { padding:5px; font-size:1.4em; background-color:light-yellow; }
</style>
To access the class use (.) and ids use (#) before the name.
If you need to set the style once and only once you want to do this:
#test
{
background-color: red;
}
If you may need to reuse it (a class) then you'll want to do something like this:
.test
{
background-color: red;
}
Then when you are ready to use it just:
<div id="test"> this is a test </div>
For # type and:
<div class="test"> this is a test </div>
For the class type.
My recommendation is to go to: http://www.w3schools.com/css/
Plenty of help about CSS there. I would try to avoid the inline css as it sometimes has a way of making artists / programmers think that it is just easier to use inline. You end up with a web page with all these inline styles that could really be centralized and reused. So be careful with inline. I do not recommend using them
精彩评论