【问题标题】:Style HR with Image用图像风格 HR
【发布时间】:2025-12-21 21:15:06
【问题描述】:

我正在努力实现尽可能接近下图的效果。

我目前通过以下代码获得以下内容,但似乎无法完全完成我需要的工作。

当前样式:

我的 CSS:

hr:after { 
    background: url('../img/green_leaf.png') no-repeat top center;
    content: "";
    display: block;
    height: 18px; /* height of the ornament */
    position: relative;
    top: -9px; /* half the height of the ornament */
    border: 0;
    color: #d7d7d7;
}

我想加粗线条,如果可能的话,在图像周围添加空间(不要让 green_leaf.png 有白色背景)。

【问题讨论】:

标签: css


【解决方案1】:

如何在hr 元素中设置图像,并使用:before:after 创建线条?这样您就不必在图像上设置背景来覆盖一行。

工作示例:

hr { 
    background: url('http://i.stack.imgur.com/37Aip.png') no-repeat top center;
    background-size: contain;
    display: block;
    height: 18px;
    border: 0;
    position: relative;
}
hr:before,
hr:after {
    content: '';
    display: block;
    position: absolute;
    background: #d7d7d7;
    height: 2px;
    top: 8px;
}
hr:before {
    left: 0;
    right: 50%;
    margin-right: 10px;
}
hr:after {
    right: 0;
    left: 50%;
    margin-left: 10px;
}
<hr />

【讨论】:

  • 正是我想要的!我想避免添加额外的 DIV 并保持简单地使用 HR 标签的能力,这完全根据需要工作!非常感谢!
【解决方案2】:

你可以在这篇帖子Custom <hr> with image/character in the center找到答案

我修改了它,我得到了这个:

hr {
  no-repeat top center;
  text-align: center; /* horizontal centering */
  line-height: 1px; /* vertical centering */
  height: 1px; /* gap between the lines */
  border-width: 1px 0; /* top and bottom borders */
  border-style: solid;
  border-color: #676767;
}

hr:after {
  content: ""; /* section sign */
  background: url('smiley.gif') no-repeat top center;
  display: inline; /* for vertical centering and background knockout */
  background-color: white; /* same as background color */
  padding: 0 2em; /* size of background color knockout */
}

注意padding: 0 2em;background-color: white;

【讨论】:

    【解决方案3】:

    如果你像这样设置它,并在图像上指定背景颜色以匹配页面背景中的任何颜色(可能是白色),它看起来会很好:

    HTML

    <div class='hr'>
        <hr>
        <img src='../img/green_leaf.png' alt=''>
    </div>
    

    CSS

    hr {
        border:none;
        border: 1px solid #d7d7d7;
    }
    
    .hr { 
        text-align: center;
    }
    
    .hr img {
        position: relative;
        top: -18px;
        background:white;
        padding:0 5px;
    }
    

    结果:

    Fiddle

    【讨论】: