简体   繁体   English

如何定位 html 元素 class 名称而不是元素?

[英]How can I target html element class names instead of elements?

I have this code but it targets all <li> and <a> elements, how can I make it target a class instead of targeting the element?我有这段代码,但它以所有<li><a>元素为目标,我怎样才能让它以 class 为目标而不是以元素为目标?

I want to have the same exact effect.我想要完全相同的效果。

This is my html & css:这是我的 html & css:

 ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #F0E68C; } li { float: left; } li a { display: block; color: Black; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover { background-color: #FFD750;
 <nav> <ul> <li><a class="active" href="index.html">Home</a></li> <li><a href="boyshome.html">Boys Campus</a></li> <li><a href="girlshome.html">Girls Campus</a></li> <li><a href="calculator.html">GPA Calculator</a></li> </ul> </nav>

If you don't want to target all li a elements and only a specific class name, you can have this instead:如果您不想定位所有li a元素而只定位特定的 class 名称,则可以改为:

li a.active {                 // or just a.active {...}
    display: block;
    color: Black;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a.active:hover {
  background-color: #FFD750;

a.active {...}             // or just .active, this will target the class name

There are different ways to select your HTML elements in the DOM. DOM 中的 select 和 HTML 元素有不同的方法。

  • You can select ids with #你可以使用# select ids
  • You can select classes with .您可以使用 select 节课.
  • You can select all elements with a tag, like li你可以 select 所有带有标签的元素,比如li

Here is an example:这是一个例子:

<li id="first" class="listElement">First element</li>
<li class="listElement active">Second element</li>
#first {
    color: red;
}
.active {
    background: yellow;
}
.listElement {
    padding: 5px;
}

li {
    font-size: 14px;
}

You can target any class by using .<class> .您可以使用.<class>定位任何 class。 So you can do something like:所以你可以这样做:

  .active {
      <Desired style definition>
   }

This will add the styling to all the elements with the class active .这将为 class active的所有元素添加样式。 Also note if you want to target any element by it's Id then use #<id> instead of dot .<class>另请注意,如果您想通过其 Id 定位任何元素,请使用#<id>而不是点.<class>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM