html - CSS——关于对特定样式规范使用多个小类或对常用元素使用具有完整样式的单个类的意见

标签 html css

对于令人困惑的标题感到抱歉,如果问题过于模糊和开放式,我深表歉意。问题既涉及良好的编码风格,也涉及哪种性能更好,但如果两者存在差异,我很乐意得到答案。

如果我有多个具有相同样式的 div 实例,是否最好有多个类并根据需要应用这些类,例如。

.blueBackgrnd {
    background-color:blue;
}

.alignCenter {
    text-align:center;
}
smallerSize {
    height:50px;
    width:80%;
    margin: auto
}
largerSize {
    height:100px;
    width:80%;
    margin: auto
}

还是为将被多次使用的 div 指定一个类会更好,即使这些样式属性在 CSS 文件中重复多次?

largeSampleDiv {
  height:100px;
  width:80%;
  margin: auto;
  background-color:blue;
  text-align:center;
}
smallSampleDiv {
  height:50px;
  width:80%;
  margin: auto;
  background-color:blue;
  text-align:center;
}

或者两者兼而有之?还是根本不重要?

感谢您的帮助。

最佳答案

根据经验,尽可能不要复制 CSS 代码。这使得用户可以下载更大的 css 文件(对严肃元素有影响)。而且,类太多会使使用源代码变得更加困难。

这个

.largeSampleDiv {
  height:100px;
  width:80%;
  margin: auto;
  background-color:blue;
  text-align:center;
}
.smallSampleDiv {
  height:50px;
  width:80%;
  margin: auto;
  background-color:blue;
  text-align:center;
}

我会这样做

.someDiv {
  width: 80%;
  margin: auto;
  background-color: blue;
  text-align: center;
}

.small {
  height: 50px;
}
.large {
  height: 100px;
}

此外,此页面可能有用 https://google.github.io/styleguide/htmlcssguide.xml#HTML_Formatting_Rules

关于html - CSS——关于对特定样式规范使用多个小类或对常用元素使用具有完整样式的单个类的意见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40229089/

相关文章:

css - 将 div 的高度作为其内容或作为其父级(如果它较小)

javascript - React 功能组件中的 props 没有从父组件传递到子组件

html - WinJS.BackButton 大小

javascript - 如何修复剪刀石头布蜥蜴 spock 程序的输出表?

javascript - 如果子元素包含字符串,如何删除容器

javascript - 使用回调在 Chrome 中动态加载样式表

javascript - jquery animate - 返回到原来的位置

javascript - 问题通过链接更改嵌入式Youtube视频

html - 如何修改和设置简单表单 f.input 标签的样式

html - 如果使用 Bootstrap 选择了某些选项,则隐藏/显示内容