代码之家  ›  专栏  ›  技术社区  ›  guettli

<body>中的内部CSS?

  •  0
  • guettli  · 技术社区  · 5 年前

    传统上,您可以通过三种方式添加CSS:

    1. 外部CSS通过 <link rel="stylesheet" href="foo.css">
    2. 内部CSS通过 <style> h1 { ... } 在中 <head> 要素
    3. 内联CSS通过 style="..." 特定元素的属性

    内联CSS的缺点是我不能使用CSS类,这是我需要做的事情。有没有办法定义内部CSS(例如 <style></style> 中的片段 <body> 要素

    这对我来说会容易得多,因为我可以在服务器代码中使用方法创建一个自包含的HTML片段。这种方法是必要的,因为我无法控制 <头部> 部分它由一种商业产品所有。我只能在中插入内容 <身体> .

    实例

    <div>
     <style>
      .myclass {...}
     </style>
     <div class="myclass">...</div>
    </div>
    

    相关的 https://htmx.org/essays/locality-of-behaviour/

    我看过其他网站(比如 https://amazon.com )其中它们的内部似乎有几个样式标记 <身体> .

    理论与实践之间存在巨大差距。许多网站使用 <style> 体内。

    编辑们决定反对。但也许未来会有变化: https://github.com/whatwg/html/issues/1605

    0 回复  |  直到 4 年前
        1
  •  7
  •   tom    5 年前

    在这个前提下,你不在乎无效的HTML与 <style> 在…内 <body> (这并不罕见),您可以分配唯一的标识符,即:

    <style>
      .my-class-1 {
        color: gold;
      }
    </style>
    <div class="my-class-1">Fragment Content</div>
    
    <style>
      .my-class-2 {
        color: tomato;
      }
    </style>
    <div class="my-class-2">Fragment Content</div>
    
    <div class="my-fragment-1">
      <style>
        .my-fragment-1 .my-class {
          color: teal;
        }
      </style>
      <div class="my-class">Fragment Content</div>
    </div>
    
    <div class="my-fragment-2">
      <style>
        .my-fragment-2 .my-class {
          color: hotpink;
        }
      </style>
      <div class="my-class">Fragment Content</div>
    </div>
    
    <style id="my-style-1">
      #my-style-1 + div {
        color: orangered;
      }
    </style>
    <div>Fragment Content</div>
    
    <style id="my-style-2">
      #my-style-2 + div {
        color: indigo;
      }
    </style>
    <div>Fragment Content</div>
        2
  •  0
  •   Timothy Alexis Vass    5 年前

    它将在html5中工作,即使它在html4中被视为无效。
    我现在工作的地方有一个例子。

    我们正在为图书馆目录中的一些书籍添加幻灯片,因为这是用插件完成的,所以唯一可能的样式方式是包含 <style> 用html阻止,因为这个插件没有也不应该访问 <head> 它是为CMS设计的。

    然而,由于CMS构建方式的局限性,该解决方案是最后的手段,应予以避免。

        3
  •  0
  •   Bogdan B    5 年前

    难道你不能用Javascript瞄准head元素并以编程方式插入一个样式吗?

    <script>
      var head = document.querySelector('head')[0];
      var css = 'div { background: red; }',
        
      var style = document.createElement('style');
    
      style.appendChild(document.createTextNode(css));
    
      head.appendChild(style) ;
    
    </script>
    
        4
  •  0
  •   dhruvkrishnavaid    4 年前

    据我所知,从你的描述中,你无法访问 <head>...</head> 元素,但您可以自由编辑正文。此外,您希望使用CSS3类,但使用内联CSS,则无法使用。
    我在纯HTML/CSS中找不到方法,所以我建议您使用JQuery。

    <script async src="https://cdn.statically.io/libs/jquery/3.6.0/jquery.min.js" />
    <script>$('head').append('<style>/*Your styles here*/</style></script>');
    


    现在,将类添加到html元素中,并编辑 <style /> 标签
    此外,将此脚本放在的末尾 <body> 这样你就可以避免把它放在中间可能引起的奇怪问题。除息的
    但请记住,这会改变你的头脑 之后 用户已经加载了页面。因此,从理论上讲,用户首先会看到一个没有样式的丑陋的html页面,然后加载样式,他们会看到有样式的页面。
    有关更多解释,请查看官方文档: https://api.jquery.com/append/

        5
  •  0
  •   Amanda    4 年前

    你的例子应该有效。我使用自定义html处理WordPress,其中所有自定义代码都进入 <body> 标记,并且类似的样式应该在每个页面中工作(添加更多的div只是为了显示一个示例,即一个样式标记可以容纳div中所有div的类):

    <div> 
       <style> 
          .className { ... }
          .classNameTwo{ ... } 
          .classNameThree{ ... }
       </style>
       <div class="className"></div>
       <div class="classNameTwo">
          <div class="classNameThree"></div>
       </div>
    </div>
    
        6
  •  0
  •   Brandon McConnell    4 年前

    你的问题的简单答案是“是”,我将在下面的几个例子中详细说明这一点。A. <style> 标签将在您将其放置在 <head> 或者 <body> .

    放置在中的样式标记 <身体> 从技术上讲,标记确实违反了HTML语法规则,它在实践中非常常见,甚至在一些大公司中也是如此。

    有几种不同的方法可以包括 <身体> 数量 <样式> 标记。

    1.纯HTML <样式> 标记(静态方法)

    如果你已经写好了所有需要的样式,并且不需要动态的部分,你可以简单地将这些样式写入 <样式> 静态标记,并将其包含在代码中,如下例所示:

    <html>
      <head></head>
      <body>
        <div class="custom-widget">
          <h1>This is a title</h1>
          <p>This is some text.</p>
          <style>
            .custom-widget {
              display: block;
              padding: 20px;
              border: 5px double red;
            }
            .custom-widget h1 {
              text-transform: uppercase;
            }
            .custom-widget h1::first-letter {
              font-size: 150%;
            }
            .custom-widget p {
              font-style: italic;
            }
          </style>
        </div>
      </body>
    </html>

    2.将风格写成 <样式> 使用JavaScript标记为文本

    如果您需要将样式加载到 <样式> 动态标记,您只需要创建后不需要更改太多的纯文本样式。您可以创建 <样式> 块,然后根据需要将CSS样式注入为纯文本,如下例所示:

    const counter = document.getElementById('counter');
      let count = +counter.dataset.count;
    const customWidgetStyle = document.querySelector('.custom-widget style'),
          countdown = setInterval(() => {
            if (count--) {
              counter.innerText = `Importing CSS in ${count}…`;
            } else {
              clearInterval(countdown);
              counter.remove();
              customWidgetStyle.innerHTML = `
                .custom-widget {
                  display: block;
                  padding: 20px;
                  border: 5px double red;
                }
                .custom-widget h1 {
                  text-transform: uppercase;
                }
                .custom-widget h1::first-letter {
                  font-size: 150%;
                }
                .custom-widget p {
                  font-style: italic;
                }
              `;
            }
          }, 1000);
    <html>
      <head></head>
      <body>
        <div class="custom-widget">
          <h1>This is a title</h1>
          <p>This is some text.</p>
          <style></style>
        </div>
        <span id="counter" data-count="3">Importing CSS in 3…</span>
      </body>
    </html>

    3.将cssRules样式创建为 <样式> 使用JavaScript标记 CSSStyleSheet.insertRule() 方法

    如果您在添加样式时需要更大的灵活性,可以使用 CSSStyleSheet.insertRule() ( MDN docs ),这将动态地允许您更细粒度地添加和管理样式。对于您的特定需求来说,这可能有些过头了,但在使用CSSOM时有很多功能、灵活性和控制能力。

    以下是此方法的一个示例,其中我使用 addStylesheetRules 在MDN文档页面上定义的函数示例,用于标题下的insertRule 示例 , here :

    const addStylesheetRules = (rules, stylesheet) => {
      if (stylesheet === undefined) {
        const style = document.createElement('style');
        stylesheet = style.sheet;
        document.head.appendChild(style);
      }
      for (let i = 0; i < rules.length; i++) {
        let j = 1,
            propStr = '';
            rule = rules[i];
        const selector = rule[0];
        if (Array.isArray(rule[1][0])) {
          rule = rule[1];
          j = 0;
        }
        for (let pl = rule.length; j < pl; j++) {
          const prop = rule[j];
          propStr += prop[0] + ': ' + prop[1] + (prop[2] ? ' !important' : '') + ';\n';
        }
        stylesheet.insertRule(selector + '{' + propStr + '}', stylesheet.cssRules.length);
      }
    }
    
    const customWidget = document.querySelector('.custom-widget'),
          customWidgetStyleTag = document.createElement('style');
    customWidget.appendChild(customWidgetStyleTag);
    const customWidgetStylesheet = customWidgetStyleTag.sheet;
    addStylesheetRules([
      ['.custom-widget',
        ['display', 'block'],
        ['padding', '20px'],
        ['border', '5px double red']
      ],
      ['.custom-widget h1',
        ['text-transform', 'uppercase']
      ],
      ['.custom-widget h1::first-letter',
        ['font-size', '150%']
      ],
      ['.custom-widget p',
        ['font-style', 'italic']
      ]
    ], customWidgetStylesheet);
    <html>
      <head></head>
      <body>
        <div class="custom-widget">
          <h1>This is a title</h1>
          <p>This is some text.</p>
        </div>
      </body>
    </html>

    请让我知道,如果有更多的上下文我可以添加,以更好地回答你的问题。