使用之前和之后在伪元素之后做一条线

时间:2015-02-10 14:45:33

标签: html css

我正在使用伪元素:before:after在标题之前和之后绘制一条线。它正在使用图像:

.mydiv::before {
content: url(img/line.png);}
.mydiv::after {
content: url(img/line.png);}

结果如下:

you can see befor and after the 1px white horizontale line

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

The line reach reach the both sides of the div

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

.mydiv img {
  width: 100%;
  height: auto;
}

3 个答案:

答案 0 :(得分:16)

你不需要: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;
}
<div id="header">
   <h3>Last Projects</h3>
</div>

答案 1 :(得分:1)

如果您需要<h3>标题以具有透明背景-您可以同时使用:before: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;
}
<div id="header">
  <h3>Last Projects</h3>
</div>

答案 2 :(得分:0)

<style>
.mydiv::before{
    content: '';
    position: absolute;
    left: 0;
    width: 100%;
    height: 2px;
    bottom: 1px;
    background-color: black;
}
</style>

<div class="mydiv">About us</div>