将形状与 CSS 组合

Combine shapes with CSS

我用 CSS 创建了一个黑条:

#bg #bar {
top: 300px;
width: 7.5em;
height: 1em;
left: 50%;
margin-left: -3.75em;
margin-top: -0.5em;
position: fixed;
background-color: #333333;
/*border: 1px solid black;*/
z-index: 1;

}

我想在两边加一个白圈。是这样的: http://imgur.com/a/je00B 因为我想旋转整个图像,所以我想将所有内容组合在一个对象中(可能标记为#bar)。

可能吗?怎么样?

您可以使用 :before:after 伪元素来创建圆并 position: absolute 来定位它们。

#bar {
  width: 7.5em;
  height: 1em;
  margin: 50px;
  position: relative;
  background-color: #333333;
}
#bar:after,
#bar:before {
  content: '';
  background: white;
  height: 1em;
  width: 1em;
  position: absolute;
  border-radius: 50%;
  top: 0;
}
#bar:after {
  right: 0;
}
#bar:before {
  left: 0;
}
<div id="bar"></div>

另一种定位伪元素而不是 position: absolute 的方法是使用 Flexbox 并在父元素上设置 justify-content: space-between

#bar {
  width: 7.5em;
  height: 1em;
  margin: 50px;
  display: flex;
  justify-content: space-between;
  background-color: #333333;
}
#bar:after,
#bar:before {
  content: '';
  background: white;
  height: 1em;
  width: 1em;
  border-radius: 50%;
}
<div id="bar"></div>

#box {
  width: 200px;
  height: 200px;
  background: steelblue;
  margin: 50px auto;
  position: relative;
  }
#box:before {
  content: '';
  display: block;
  width: 200px;
  height: 200px;
  background: steelblue;
  position: absolute;
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  }
<div id="box"></div>