CSS 内联样式与类之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3142710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:18:40  来源:igfitidea点击:

What's the difference between inline styles vs classes?

cssinline-styles

提问by Corey Hart

In my head, I've always known to use classes over inline styles for any project. But are there any effective differences between the two?

在我的脑海中,我一直都知道在任何项目中使用类而不是内联样式。但是两者之间有什么有效的区别吗?

采纳答案by gblazex

There is a simple reason. The point of CSS is to separate the content (HTML) from the presentation (CSS). It's all about accessibility and code reuse.

有一个简单的原因。CSS 的重点是将内容 (HTML) 与演示文稿 (CSS) 分开。这完全是关于可访问性和代码重用

回答by tylerl

First of all:

首先:

  • If the HTML is built or generated independent of the overall site design (e.g. shared template code), then add reasonably-named classes and IDs, linked exclusively to external stylesheet(s). Use sufficient elements to allow for arbitrary CSS manipulation. For example, see the CSS Zen Garden. This applies to ALL CMSes, programs, scripts, and other dynamically-generated site content.The HTML output must contain absolutely no styling or layout of any sort at all. No exceptions.
  • 如果 HTML 的构建或生成独立于整个站点设计(例如共享模板代码),则添加合理命名的类和 ID,专门链接到外部样式表。使用足够的元素以允许任意 CSS 操作。例如,请参阅CSS Zen Garden这适用于所有 CMS、程序、脚本和其他动态生成的站点内容。HTML 输出必须完全不包含任何样式或布局。没有例外。

Assuming you're dealing with static content, then:

假设您正在处理静态内容,那么:

  • If there's any way you can reuse the style, make it a class and link to a stylesheet.

  • If there's no way would ever reuse the style (it's a one-off thing that doesn't make sense anywhere else) then use a <style>block that references the element's #id.

  • If the CSS attribute only makes sense in the context of the surrounding HTML (e.g. some usages of clear:) then I inline the style into the element.

  • 如果有任何方法可以重用样式,请将其设为类并链接到样式表。

  • 如果没有办法重用样式(这是一次性的东西,在其他任何地方都没有意义),那么使用<style>引用元素#id 的块。

  • 如果 CSS 属性仅在周围 HTML 的上下文中有意义(例如 的某些用法clear:),那么我将样式内联到元素中。

A lot of people call this heresy, just like a lot of people denounce any use of gotoin modern programming languages.

很多人称之为异端邪说,就像很多人谴责goto现代编程语言中的任何使用一样。

However, rather than subscribing to stylistic dogma, my view is you should chose the method based on your circumstances that decreases your overall workload the most. Stylesheets add a level of indirection that makes site-level changes easy and helps build consistency. But if you have several dozen classes on each page that are only used in one place, then you're actually increasing your workload, not decreasing it.

但是,我的观点是,您应该根据自己的情况选择最能减少整体工作量的方法,而不是遵循文体教条。样式表添加了一个间接级别,使站点级别的更改变得容易并有助于建立一致性。但是,如果您在每个页面上有几十个只在一个地方使用的类,那么您实际上是在增加而不是减少工作量。

In other words, don't do something dumb and confusing just because people tell you it's the right way to do it.

换句话说,不要仅仅因为人们告诉你这是正确的做法就去做一些愚蠢和令人困惑的事情

回答by Anurag

If the choice was there, my first preference will be classes/other selectors. However, there are situations where inline styles are the only way to go. In other situations, just a CSS class by itself requires too much work, and other types of CSS selectors make more sense there.

如果有选择,我的首选将是类/其他选择器。但是,在某些情况下,内联样式是唯一的出路。在其他情况下,仅仅一个 CSS 类本身需要太多的工作,而其他类型的 CSS 选择器在那里更有意义。

Suppose you had to zebra stripe a given list or table. Instead of applying a particular class to each alternate element or row, you could simply use selectors to do the job. That will keep the code simple, but it won't be using CSS classes. To illustrate the three ways:

假设您必须对给定的列表或表格进行斑马条纹。您可以简单地使用选择器来完成这项工作,而不是将特定的类应用于每个替代元素或行。这将使代码保持简单,但不会使用 CSS 类。要说明的三种方式

Using only class

仅使用类

.alternate {
    background-color: #CCC;
}

<ul>
    <li>first</li>
    <li class="alternate">second</li>
    <li>third</li>
    <li class="alternate">fourth</li>
</ul>

Using class + structural selectors

使用类 + 结构选择器

.striped :nth-child(2n) {
    background-color: #CCC;
}

<ul class="striped">
    <li>first</li>
    <li>second</li>
    <li>third</li>
    <li>fourth</li>
</ul>

Using inline styles

使用内联样式

<ul>
    <li>first</li>
    <li style="background-color: #CCC">second</li>
    <li>third</li>
    <li style="background-color: #CCC">fourth</li>
</ul>

The second way looks the most portable and encapsulated to me. To add or remove stripes from any given container element, simply add or remove the stripedclass.

第二种方式在我看来是最便携和封装的。要从任何给定的容器元素添加或删除条纹,只需添加或删除striped类。

However, there are cases where inline styles not only make sense, but are the only way to go. When the set of possible values is huge, it will be stupid to try to make classes in advance for each possible state. For example, a UI that allows the user to dynamically place certain items anywhere on the screen by dragging. The item will have to be positioned absolutely or relatively with actual coordinates such as:

但是,在某些情况下,内联样式不仅有意义,而且是唯一的出路。当可能值的集合很大时,尝试预先为每个可能的状态创建类将是愚蠢的。例如,允许用户通过拖动将某些项目动态放置在屏幕上的任何位置的 UI。该项目必须绝对或相对于实际坐标定位,例如:

<div style="position: absolute; top: 20px; left: 49px;">..</div>

Surely, we could use classes for each possible position the div can take, but that's not recommended. And one can easily see why:

当然,我们可以为 div 可以采取的每个可能的位置使用类,但不推荐这样做。人们可以很容易地看出原因:

.pos_20_49 {
    top: 20px;
    left: 49px;
}
.pos_20_50 {
    top: 20px;
    left: 50px;
}
// keep going for a million such classes if the container size is 1000x1000 px

<div class="pos_20_49">..</div>

回答by Chris

Use common sense.

使用常识。

Everyone knows that presentation and content should, in an ideal world, be separated. Everyone also knows that this doesn't work very well a lot of the time. We all know that you're supposed to use divs rather than tables for layout, but we also know that for any circumstance where you don't have full control over the content it just doesn't work properly.

每个人都知道,在理想的世界中,演示文稿和内容应该分开。每个人也都知道这在很多时候效果不佳。我们都知道您应该使用 div 而不是表格进行布局,但我们也知道,对于您无法完全控制内容的任何情况,它都无法正常工作。

Downloading a 500k style sheet to style one element because you've taken every possible style and stuck it in a style sheet will kill your page, downloading 500 smaller style sheets to style your page because you need them all will also kill your page.

下载 500k 样式表来设置一个元素的样式,因为您已经采用了所有可能的样式并将其粘贴在样式表中,这将杀死您的页面,下载 500 个较小的样式表来设置您的页面样式,因为您需要它们也会杀死您的页面。

Reuse is great in concept, but the reality is that it's only useful in certain contexts. This applies equally to pretty much anywhere the concept exists. If your project does what you want it to do, does so in every reasonable browser, does so in an efficient way, and does so reliably, then you're good to go, it's not dramatically harder to refactor css than is is code.

重用在概念上很好,但现实是它只在某些情况下有用。这同样适用于几乎所有存在该概念的地方。如果您的项目按照您的意愿执行,在每个合理的浏览器中执行,以高效的方式执行,并且执行得如此可靠,那么您就可以开始了,重构 css 并不比代码难得多。

回答by Brock Adams

I can't think of any pros for inline styles.

我想不出任何内联样式的优点。

CSS is all about Progressive Enhancement, and not repeating yourself (DRY).

CSS 是关于Progressive Enhancement 的,而不是重复你自己 (DRY)

With stylesheets, Changing the look becomes as easy as changing one line in the HTML code. Make a mistake or the client doesn't like the change? revert to the old stylesheet.

使用样式表,更改外观就像更改 HTML 代码中的一行一样简单。犯了错误或客户不喜欢更改?恢复到旧样式表。

Other advantages:

其他优点:

  1. Your site can automagically adjust to different media, such as for printout and for hand-held devices.

  2. Conditionally-included CSS fixes, for that gawd-awful browser-that-shall-not-be-named, become a snap.

  3. Your users can easily customize the site with plugins like Stylish.

  4. You can more easily reuse or share code from site to site.

  1. 您的站点可以自动适应不同的媒体,例如打印输出和手持设备。

  2. 有条件地包含的 CSS 修复,对于那个令人讨厌的浏览器-不应命名的,变得轻而易举。

  3. 您的用户可以使用 Stylish 等插件轻松自定义站点。

  4. 您可以更轻松地在站点之间重用或共享代码。

回答by Justin Johnson

I can think of only two situations where inline styles are appropriate and/or reasonable.

我只能想到两种内联样式合适和/或合理的情况。

  1. If inline styles are programmatically applied. For example, showing and hiding elements with JavaScript, or applying content specific styles when rendering a page (see #2).

  2. If inline styles complete a class definition for a single element in cases where id's are neither appropriate or reasonable. For example, setting the background-imageof a element for a single image in a gallery:

  1. 如果以编程方式应用内联样式。例如,使用 JavaScript 显示和隐藏元素,或在呈现页面时应用特定于内容的样式(参见 #2)。

  2. 如果内联样式在 id 既不合适也不合理的情况下完成单个元素的类定义。例如,background-image为图库中的单个图像设置元素的 :

HTML

HTML

<div id="gallery">
    <div class="image" style="background-image:url(...)">...</div>
    <div class="image" style="background-image:url(...)">...</div>
    <div class="image" style="background-image:url(...)">...</div>
</div>

CSS

CSS

#gallery .image {
    background: none center center;
}

回答by Xeoncross

Inline Stylesare definitely the way to go. Just look at http://www.csszengarden.com/- that would never have been possible with classesand external style sheets...

内联样式绝对是要走的路。只需看看http://www.csszengarden.com/-外部样式表永远不可能做到这一点......

or wait...

或者等等...

回答by Jesse Squire

Assuming that you are using external stylesheets, an additional benefit on top of those previously mentioned is caching. The browser will download and cache your stylesheet once, and then use the local copy each additional time it is referenced. This allows your markup to be more compact. Less markup to transfer and parse means a more responsive feel and better experience for your users.

假设您使用的是外部样式表,那么除了前面提到的那些之外,还有一个额外的好处就是缓存。浏览器将下载并缓存您的样式表一次,然后在每次引用时使用本地副本。这使您的标记更加紧凑。更少的传输和解析标记意味着更灵敏的感觉和更好的用户体验。

回答by Praveen Rai

With the addition of Custom properties to CSS, now there's another use case. One might want to use inline style to set custom properties.

通过向 CSS 添加自定义属性,现在还有另一个用例。人们可能希望使用内联样式来设置自定义属性。

For e.g. below i am using CSS grid to align HTML Lists and Div blocks and i wish to have flexibility in the HTML (Just the way BootStrap or any other framework provides) as this HTML is dynamically generated by application.

例如,下面我使用 CSS 网格来对齐 HTML 列表和 Div 块,我希望在 HTML 中具有灵活性(就像 BootStrap 或任何其他框架提供的方式一样),因为此 HTML 是由应用程序动态生成的。

CSS :

CSS :

:root{
--grid-col : 12;
--grid-col-gap:1em; 
--grid-row-gap:1em;
--grid-col-span:1;
--grid-row-span:1;
--grid-cell-bg:lightgray;
}

.grid{
    display: grid;
    grid-template-columns: repeat(var(--grid-col), 1fr);
    column-gap: var(--grid-col-gap);
    row-gap: var(--grid-row-gap);
}

.grid-item{
    grid-column-end: span var(--grid-col-span);
    grid-row-end: span var(--grid-row-span);
    background: var(--grid-cell-bg);
}

HTML :

HTML :

    <ul class="grid" style="--grid-col:4">
        <li class="grid-item">Item 1</li>
        <li class="grid-item">Item 2</li>
        <li class="grid-item">Item 3</li>
        <li class="grid-item">Item 4</li>
        <li class="grid-item">Item 5</li>
        <li class="grid-item">Item 6</li>
        <li class="grid-item">Item 7</li>
        <li class="grid-item">Item 8</li>
    </ul>

In the above HTML to change the four columns to 3 i change the custom property using style attribute :

在上面的 HTML 中,将四列更改为 3 我使用样式属性更改自定义属性:

    <ul class="grid" style="--grid-col:3">
        <li class="grid-item">Item 1</li>
        <li class="grid-item">Item 2</li>
        <li class="grid-item">Item 3</li>
        <li class="grid-item">Item 4</li>
        <li class="grid-item">Item 5</li>
        <li class="grid-item">Item 6</li>
        <li class="grid-item">Item 7</li>
        <li class="grid-item">Item 8</li>
    </ul>

You can check the extended live example at https://codepen.io/anon/pen/KJWoqw

您可以在https://codepen.io/anon/pen/KJWoqw查看扩展的实时示例

回答by lastnamearya

Classes are the re-usable styles that can be added to HTML elements. e.g-

类是可以添加到 HTML 元素的可重用样式。例如-

<style> 
   .blue-text{color:Blue;}
</style>

you can use and re-use this blue-text class to any HTML element Note that in your CSS style element, classes should start with a period. In your HTML elements' class declarations, classes shouldn't start with a period. whereas inline style are like e.g-

您可以在任何 HTML 元素中使用和重复使用此蓝色文本类 请注意,在您的 CSS 样式元素中,类应以句点开头。在 HTML 元素的类声明中,类不应以句点开头。而内联样式就像例如-

<p style="color:Blue;">---</p>

So the difference between both is you can re-use classes whereas you can't re-use inline styles.

因此,两者之间的区别在于您可以重用类,而不能重用内联样式。