我有几十篇博客帖子是从WordPress网站导入的,它们使用单行粗体作为标题(没有这样标记).这是我的内容示例:

<p><strong>This is a heading. I want to apply some CSS to this line of text</strong></p>
<p>But I don't want it applied here<strong>or here</strong> because this a paragraph.</p>

我想要的就是在这些大胆的句子上加一个页边距,以澄清它们是一个章节的标题.

我不能修改的超文本标记语言(即改变他们的H3),因为这将意味着手动通过所有帖子.我需要坚持使用css来进行更改.

我试过了,这是一个相当好的解决方案.但这并不是因为示例中的小段落也被选中了,因为它只有一个&lt;strong&gt;.

p:has(strong:only-child) {
    margin-top: 20px;
}

我的 idea 是找到一种方法,排除除单一的强标签外,任何含有任何"松散文本"的标签.但我不知道如何说"松散文本"才能在:not()伪 Select 器中使用它.

我希望这条规则只影响这个边距:Image

我希望这是合理的.

推荐答案

对于您的问题,更好的解决方案是使用正则表达式查询更改为<p><strong>的数据库.

If you still want to do it on the frontend, then you won't be able to do this with css.
I wrote one of the js solutions below. But I do not guarantee that it is perfect.

document.querySelectorAll('p').forEach(p => {
  // exclude empty <p> or <p> is not has <strong>
  if (!p.hasChildNodes() || !p.querySelector('strong')) { 
    return;
  }
  const childNodes = p.childNodes;
  // check whitespace
  if (childNodes[0].nodeType === Node.TEXT_NODE || childNodes[childNodes.length - 1].nodeType === Node.TEXT_NODE) {
    p.innerHTML = p.innerHTML.trim();
  }
  if (childNodes.length === 1 && p.childNodes[0].nodeName === 'STRONG' && p.childNodes[0].textContent.trim()) {
    p.style.marginBlockStart = '20px';
  }
})
* {
  margin: 0;
}
<p> <strong>This is a heading with whitespace</strong></p>
<p>But I don't want it applied here<strong>or here</strong> because this is a paragraph.</p>
<p><strong>This is a heading</strong></p>
<p>Lorem ipsum dolor sit amet.</p>
<p><strong></strong></p>
<p>Lorem ipsum dolor sit amet.</p>

Html相关问答推荐

Angular Project中的星级 Select

如何影响flex项目中的flex-gap收缩顺序和文本换行顺序?

穿过整个屏幕的旋转线

carousel 的垂直滚动按钮居中

将文本保持在平行四边形内并遵循形状

如何从通过 find-each 方法(在 Rails 应用程序中)生成的列表创建下拉菜单?

按钮位于主 div 的底部而不是内部 Div

R 中的网页抓取数字?

当我将有序列表居中时,数字会跑到列表的另一行

更改标签标签的大小

什么没有 margin-right 和 width:100% 溢出子元素到左边?

在 SQL 中合并 HTML 表中的单元格

在 jinja 模板内的 html 表中嵌套 For 循环

使用 TailwindCSS 将徽标放在左上角,将菜单放在右上角

使用 CSS 样式化进度条

CSS 网格自动高度不适用于特定网格区域

html tailwindcss 给 li 标签添加边框

如何在不删除

标记的情况下加入 HTML 中的段落

是否可以使用纯 css 创建具有斜角效果的锯齿形边缘?

调整窗口大小时试图阻止按钮移动