Apply properties to an element only if it belongs to a class

Asked

Viewed 35 times

1

I want to apply css to these elements

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 200px;
    background-color: #f1f1f1;
}

li a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #555;
    color: white;
}

li {
    display: inline;
}

But only if you belong to an x class, how could you do this?

2 answers

2

Yes it is possible in two ways.

One case you want to put the elements inside a father div for example, then the div .classex and everything within it can be customized with your css

.classex ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 200px;
    background-color: #f1f1f1;
}

.classex li a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
}

.classex li a:hover {
    background-color: #555;
    color: white;
}

.classex li {
    display: inline;
}
<div class="classex">
  <ul>
    <li><a href="#">classe x</a></li>
  </ul>
</div>


The other way is to put the .classex in the element itself, thus

ul.classex {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 200px;
    background-color: #f1f1f1;
}

li.classex a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
}

li.classex a:hover {
    background-color: #555;
    color: white;
}

li.classex {
    display: inline;
}
<ul class="classex">
  <li class="classex"><a href="#">classe x</a></li>
</ul>

1


Inform the element along with the class you want it to belong to.

Example:

li.teste {
color: blue;
}

a.teste {
color: red;
}
<li class="teste">Teste</li>
<li>Teste</li>
<br>

<a class="teste">Teste</a>
<br>
<a>Teste</a>

In case I misunderstood your question, tell me that I change my answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.