为什么要在html中使用多个类?

问题描述 投票:-1回答:1

我是一个编程新手,我不明白为什么要在HTML中使用多个类。我的意思是即使是一个类或多个类,所有的CSS样式都只适用于同一个contenttext,那么当一个类做同样的事情时,多类有什么用?

html css coding-style
1个回答
-1
投票

我想你想问的是。

.a{
   height:20px;
   width:50px;}

.b{background:red;}
<div class="a b"></div>

为什么我使用 "a "和 "b",而不是只使用 "a",然后在.a{}中应用.b{}的代码?

可以考虑这个案例。

.head{font-size:50px;}
.green{color:green;
       margin:100px;}
<p class="head">This is an example</p>
<p class="head green">Hello World!</p>
<p class="green">i love maths</p>
<p class="green">3+3=3!</p>

所以我想把一些内容做成绿色的,一些内容做成大的。"Hello World!"这行内容都有。这就是为什么我使用了2个不同的类,这样我就不用再为 "Hello World!"重复同样的代码了。

我举的例子是一个很蹩脚的例子,但是是的,你将不得不使用多个类,这样你就可以在你的HTML中的其他标签上使用相同的CSS代码,而不重复代码。


2
投票

你使用多个类是为了让你的代码保持DRY(Don't Repeat Yourself),例如让我们说你有两个按钮,一个蓝色的主按钮和一个红色的辅助按钮。

.red-button {
  background-color: red;
  border-radius: 3px;
  color: #fff;
  padding: 10px;
}

.blue-button {
  background-color: blue;
  border-radius: 3px;
  color: #fff;
  padding: 10px;
}

这里你有重复的css。

有了多个类,你可以做这样的事情

.button {
  border-radius: 3px;
  color: #fff;
  padding: 10px;
}

.button.red {
  background-color: red;
}

.button.blue {
  background-color: blue;
}

1
投票

它允许你在需要类似特性的地方重复使用类。如果你为每个元素单独编写样式,你会有很多重复的代码。


1
投票

类是将一个元素标记为一个组的一部分的方式。一个东西可以属于多个组。

.agent {
    background: #afa;
    margin: 5px;
    padding: 5px;
    width: 10em;
    list-style: none;
}

.double-agent {
    background: #faa;
}
<ul>
  <li class="agent">Edger Raven</li>
  <li class="agent">Simon Sly</li>
  <li class="agent double-agent">Sergei Skripal</li>
  <li class="agent double-agent">Belgian Butcher</li>
  <li class="agent">Jack the Mechanic
  </li>
</ul>
© www.soinside.com 2019 - 2024. All rights reserved.