我怎样才能有一个基本标题和一个自定义标题?

How can I have a basic heading and a custom one?

我有以下 CSS 来制作一个 H1 有一条线穿过背景并且居中。我必须在我的 h1 标签之间使用 span 元素才能使其正常工作。

CSS是

h1 {
    font-size: 28px;
    font-family:'Palatino';
    font-style: italic;
    font-weight:600;
    color: #2D6A97;
    margin-bottom:60px;
    position:relative;
    text-align:center;
}

h1 span {
    background:#FDFCF8;
    padding: 0 15px;
    position: relative;
    z-index: 1;
}

h1:before {
    background:#E5DEC6;
    content: "";
    display:block;
    height: 1px;
    position:absolute;
    top:50%;
    width:100%;
}

h1:before {
    left: 0;
}

不过在其他页面上,我只想要一个普通的 H1(没有任何 CSS)。

我怎样才能改变我所拥有的,使无样式的 H1 看起来仍然正常?

理想情况下,我希望能够执行以下操作:

   <h1 class="withborder"><span>Here's my H1</span></h1>

你已经回答了:

  • 你需要给你的h1
  • 一个class

但是 如果你想让你的 h1 没有样式,那么在 CSS 中,你必须将样式应用到 class 而不是 h1,否则它将应用于您项目中的所有 h1

.class {
  font-size: 28px;
  font-family: 'Palatino';
  font-style: italic;
  font-weight: 600;
  color: #2D6A97;
  margin-bottom: 60px;
  position: relative;
  text-align: center;
}
.class span {
  background: #FDFCF8;
  padding: 0 15px;
  position: relative;
  z-index: 1;
}
.class::before {
  background: #E5DEC6;
  content: "";
  display: block;
  height: 1px;
  position: absolute;
  top: 50%;
  width: 100%;
  left: 0
}
<h1><span>Here's my H1 non-styled</span></h1>
<h1 class="class"><span>Here's my H1 styled</span></h1>

有很多不同的方式.. 尽管我可能不会向每个 h1 标签添加 classes 在我想设置 h1 标签样式的页面主体上使用 class,然后将 css.

中的 h1 作为目标

例如

<body class="styleThisPage">

并在 css

 body.styleThisPage h1 {
        font-size: 28px;
        font-family:'Palatino';
        font-style: italic;
        font-weight:600;
        color: #2D6A97;
        margin-bottom:60px;
        position:relative;
        text-align:center;
    }

body.styleThisPage h1 span {
    background:#FDFCF8;
    padding: 0 15px;
    position: relative;
    z-index: 1;
}

body.styleThisPage h1:before {
    background:#E5DEC6;
    content: "";
    display:block;
    height: 1px;
    position:absolute;
    top:50%;
    width:100%;
}



  body.styleThisPage h1:before {
        left: 0;
    }

但这只是个人喜好,取决于网站。

如果你希望一个页面有H1样式而其他页面没有,你也可以将这个样式写在文件中,并在需要它的页面中包含这个文件。或者如前所述,您可以使用 class 标记您的 H1 - 然后您需要为 class.

编写样式