CSS Fill :::背景颜色之前的

时间:2018-08-17 07:09:24

标签: html css

我正在尝试用背景色填充div :: before。 当我设置固定宽度时,它可以工作,但是如果我想:

width: auto;

它不起作用。

如果我设置了

width: 100%;

它与div重叠并填充相同的颜色。

这是我要实现的目标: enter image description here

这也是jsfiddle链接: http://jsfiddle.net/ofyt1cb8

如果将.container :: before宽度设置为固定长度,则它将起作用。但我希望它“捕捉”到自动居中的div。

这有可能吗?

整个代码:

<div class="container">
  CENTERED
</div>


.container {
  width: 300px;
  background: #000;
  color: #FFF;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
}

.container:before {
  content: "";
  position: absolute;
  left: 0;
  width: auto;
  height: 20px;
  background: #FF0000;
}

谢谢!

4 个答案:

答案 0 :(得分:2)

使用calc()vw,可以为之前的内容设置固定但可变的宽度:

.container {
  width: 300px;
  background: #000;
  color: #FFF;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  position:relative;
}

.container:before {
  content: "";
  position: absolute;
  right: 100%;
  width: calc(50vw - 150px);
  height: 20px;
  background: #FF0000;
}

我已将.container的位置设置为relative,以使:before本身在div中的位置。

right: 100%;上设置:before,确保:before.container的左侧开始向左移动。

使用calc(),我们可以进行数学计算:50vw等于视口宽度(vw)的一半,减去.containers宽度(150px)的一半将得到页面的剩余宽度。

答案 1 :(得分:1)

Flexbox可以做到

body {
  background: blue;
}

.container {
  display: flex;
  color: #FFF;
  margin-bottom: 1em;
}

.container:before,
.container:after {
  content: "";
  flex: 1;
  background: pink;
}

.container:after {
  content: "";
  flex: 1;
  background: lightgreen;
}
<div class="container">
  CENTERED
</div>

<BR/>
<div class="container">
  CENTERED HEADING
</div>

答案 2 :(得分:0)

宽度自动将不起作用,因为它没有内容。 您需要将商品的位置有所不同。

http://jsfiddle.net/ofyt1cb8/16/

.container {
  width: 300px;
  background: #000;
  color: #FFF;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  position:relative;
}

.container:before {
  content: "";
  position: absolute;
  left: -50px;;
  width: 50px;;
  height: 20px;
  background: #FF0000;
}
  • 在父级上使用position: relative
  • 将孩子相对于父对象定位。
  • 设置宽度,而不是auto0

答案 3 :(得分:0)

使用calc()。

calc()是一个CSS函数,可以在允许长度,频率,角度,时间,数字或整数值的任何地方使用。它使您可以执行带有加号(+),减号(-),乘法(*)和除法(/)的数学表达式,然后将表达式的结果用作CSS属性的值,该CSS属性接受以前的任何-提到的值。

width: calc((100% - 300px) / 2 );