【问题标题】:Use before & after Pseudo-element to make a line在伪元素之前和之后使用来制作一条线
【发布时间】:2015-04-10 15:41:05
【问题描述】:

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

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

结果如下:

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

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

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

【问题讨论】:

标签: html css


【解决方案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】:
<style>
.mydiv::before{
    content: '';
    position: absolute;
    left: 0;
    width: 100%;
    height: 2px;
    bottom: 1px;
    background-color: black;
}
</style>

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

【讨论】:

  • 考虑在您的答案中添加额外信息,使其与其他答案区分开来。就目前而言,您只是在重复已经提供的信息,而不是提供任何新的或有用的信息。
【解决方案3】:

你不需要:before:after,两者中的任何一个都足够了,正如你被告知的那样,你不需要图像。请参阅下面的方法。

#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>

【讨论】:

  • 它工作正常。我喜欢你使用背景颜色来隐藏线条的方式。谢谢
  • 如果内容被调整大小(稍微改变位置)则不起作用。有没有办法让它相对?做 position: relative 使其消失,宽度为 0。
  • @nullwriter 真实元素必须具有相对的位置属性值才能将其保留在自身中。为什么是零宽度?
猜你喜欢
  • 1970-01-01
  • 2021-08-06
  • 2016-08-14
  • 2023-03-21
  • 2018-05-22
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多