将箭头定位在一个 div 元素的中间

3
我需要在div的顶部和中间定位箭头。 div的宽度会动态变化,当我使用left:%50将箭头定位在中间时,它会添加箭头的宽度,因此结果不令人满意。 演示 代码

#wrapper {
  display: inline-block;
  position: absolute;
  padding: 1px;
  color: #000;
  border: 0px solid #cc3333;
  background-color: grey;
}
#wrapper em.out {
  position: absolute;
  left: 50%;
  top: -7px;
  display: block;
  background: transparent;
  border-left: 7px dashed transparent;
  border-right: 7px dashed transparent;
  border-bottom: 7px solid grey;
  overflow: hidden;
}
#wrapper em.inner {
  position: absolute;
  left: 50%;
  top: -7px;
  display: block;
  background: transparent;
  border-left: 7px dashed transparent;
  border-right: 7px dashed transparent;
  border-bottom: 7px solid grey;
  overflow: hidden;
}
<div id="wrapper">
  <em class="out"></em>
  <em class="inner"></em>
  <div>
    <div style="margin:1px;background-color:white;">
      <option>------John------</option>
    </div>
    <div style="margin:1px;background-color:white;">
      <option>------David------</option>
    </div>
    <div style="margin:1px;background-color:white;">
      <option>------Jennifer------</option>
    </div>
    <div style="margin:1px;background-color:white;">
      <option>------Sue------</option>
    </div>

  </div>
</div>

1个回答

1
你只需要在 #wrapper em.inner#wrapper em.out 类上添加 transform: translate(-50%); 就行了!非常简单 :)

#wrapper {
  display: inline-block;
  position: absolute;
  padding: 1px;
  color: #000;
  border: 0px solid #cc3333;
  background-color: grey;
}
#wrapper em.out {
  position: absolute;
  left: 50%;
  top: -7px;
  display: block;
  background: transparent;
  border-left: 7px dashed transparent;
  border-right: 7px dashed transparent;
  border-bottom: 7px solid grey;
  overflow: hidden;
  transform: translate(-50%);
}
#wrapper em.inner {
  position: absolute;
  left: 50%;
  top: -7px;
  display: block;
  background: transparent;
  border-left: 7px dashed transparent;
  border-right: 7px dashed transparent;
  border-bottom: 7px solid grey;
  overflow: hidden;
  transform: translate(-50%);
}
<div id="wrapper">
  <em class="out"></em>
  <em class="inner"></em>
  <div>
    <div style="margin:1px;background-color:white;">
      <option>------John Doe------</option>
    </div>
    <div style="margin:1px;background-color:white;">
      <option>------David------</option>
    </div>
    <div style="margin:1px;background-color:white;">
      <option>------Jennifer------</option>
    </div>
    <div style="margin:1px;background-color:white;">
      <option>------Sue------</option>
    </div>

  </div>
</div>


那很棒。真的很好。 - tablexyz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接