在伪元素之前和之后使用来创建一条线

Gui*_*ume 10 html css

我使用伪元素:before:after前一个标题后画一条线.它正在使用图像:

.mydiv::before {
content: url(img/line.png);}
.mydiv::after {
content: url(img/line.png);}
Run Code Online (Sandbox Code Playgroud)

结果如下:

你可以看到前后1px白色水平线

但是,我希望该行扩展并在标题之前和之后填写整个div,如下所示:

线路到达div的两侧

有没有办法为图像指定一个百分比来拉伸?我试试这个,但它不起作用:

.mydiv img {
  width: 100%;
  height: auto;
}
Run Code Online (Sandbox Code Playgroud)

Sle*_*eek 18

你并不需要同时:before:after,无论是2的就足够了,当你一直在说,你不需要的图像.请参阅下面的方法.

#header {
    width: 100%;
    height: 50px;
    margin: 50px 0;
    text-align: center;
    font-size: 28px;
    position: relative;
    background-color: #57585C;
}

#header:after {
    content: '';
    width: 100%;
    border-bottom: solid 1px #fff;
    position: absolute;
    left: 0;
    top: 50%;
    z-index: 1;
}

h3 {
    background-color: #57585C; /* Same as the parents Background */
    width: auto;
    display: inline-block;
    z-index: 3;
    padding: 0 20px 0 20px;
    color: white;
    position: relative;
    font-family: calibri;
    font-weight: lighter;
    margin: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div id="header">
   <h3>Last Projects</h3>
</div>
Run Code Online (Sandbox Code Playgroud)


foc*_*yle 8

如果您需要<h3>标题具有透明背景 - 您可以同时使用:beforeand:afterdisplay: flex

有关您的更多信息,flex-grow请阅读此处https://developer.mozilla.org/en-US/docs/Web/CSS/flex

body {
  background: linear-gradient(0.25turn, #3f87a6, #000000, #f69d3c); /* example of custom background */
}

#header {
  display: flex;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center; /* making vertical centerign of all children */
}

#header::before, #header::after {
  content: '';
  flex: 1 1 auto; /* the first digint is 'flex-grow: 1', helps elemet to occupy all free space */ 
  border-bottom: solid 1px #fff;
}

h3 {
  flex: 0 1 auto; /* the first digint is flex-grow: 0 */ 
  padding: 0 15px 0 15px;
  color: #fff;
}
Run Code Online (Sandbox Code Playgroud)
<div id="header">
  <h3>Last Projects</h3>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 我肯定会推荐这个解决方案。即使您认为不需要标题透明,但面向未来也没什么坏处。优雅的加分。 (2认同)