ShellRox
ShellRox

Reputation: 2602

How can i apply css stylesheet to single specific element?

I am new to web development, I have tried css stylesheet with simple HTML element and it worked well, when i specified element name:

label {
    color: green;
}

this would be applied to all label tags, but is there any way to apply stylesheet to single element? For example: There are 2 labels, one is green and second is blue, How can this be achieved?

Upvotes: 5

Views: 17602

Answers (4)

user6213434
user6213434

Reputation:

You can do that using html attributes such:

  • class, id, data-nameOFData for any of HTML element

.class {
  color: blue
}

#id {
  color: green
}

div[data-test] {
  color: yellow
}
<div class="class">class</div>
<div id="id">id</div>
<div data-test>data</div>

  • name , type and for for input elements

label[for="textInput"] {
  color: aqua
}

input[type="text"] {
  color: brown
}
<label for="textInput">label</label>
<br>
<input type="text" name="textInput" value="name" />

  • href for anchors tags and src for images

a {
  padding: 10px;
  background-color: deepskyblue
}

a[href*="google"] {
  background-color: yellow
}
<a href="http://www.youtube.com">youtube</a>
<a href="http://www.google.com">google</a>


Also you can select any element without defining any attribute for it if you know his index using CSS pseudo selectors :first-child , :nth-child(n) , :last-child , :first-of-type , :nth-of-type(n) , :last-of-type , :nth-of-type(even), :nth-child(odd) MDN , w3Schools.

div {
  width: 100px;
  height: 50px;
}

div:nth-of-type(even) {
  background-color: cornflowerblue
}

div:nth-child(3) {
  background-color: coral
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>

Upvotes: 1

Emirhan &#214;zlen
Emirhan &#214;zlen

Reputation: 484

There's lots of ways to accomplish this. There's lots of css selectors like ID, classes... See css selectors reference

Best way to achieve what you want is to use classss. See classes

.red {
      color: red;
}
.blue {
      color: blue;
}
<label class="blue">
    I'm blue
</label>
<label class="red">
  I'm red
</label>

    

Upvotes: 4

rageit
rageit

Reputation: 3601

Use id of the element if you want to target a specific element. Example:

#labelId{
    color: green;
}

<label id="labelId">Some Text</label>

Alternatively, you can also provide specific class name to the element. Example:

.label-class{
    color: green;
}

<label class="label-class">Some Text</label>

Upvotes: 2

Pete Howell
Pete Howell

Reputation: 41

You could do

    <label name="green">
    label[name=green]{
        color:green;
    }

Upvotes: 2

Related Questions