使用CSS显示箭头头部

5
我想在我的内容DIV旁边显示一个箭头。应该类似于这样 - enter image description here 我的问题是当我向DIV中添加内容时,我无法保持箭头垂直居中于内容DIV。
这是我的HTML和CSS:
<div id="mybox">
  <p></p>
</div>


#mybox {
    width:200px;   
    min-height:100px;
    background-color:green;
    position:relative;
}

#mybox:after {
    content:"";
    border-top: 20px solid transparent;
    border-bottom: 20px solid transparent;
    position: absolute;
    border-left: 20px solid #f00;
    width: 0; 
    height: 0; 
    right: -20px;
    top: 20px; 
}

有谁能告诉我如何解决这个问题吗?

CSSDESK

谢谢。

3个回答

6

由于箭头的高度已知,您可以使用top50%,然后使用负的margin-top来偏移箭头的高度:

这里有示例 - 现在适用于动态内容。

#mybox:after {
    content:"";
    border-top: 20px solid transparent;
    border-bottom: 20px solid transparent;
    position: absolute;
    border-left: 20px solid #f00;
    width: 0;
    height: 0;
    right: -20px;
    top: 50%;
    margin-top: -20px;
}

另外,如果箭头的高度未知,您可以使用以下方法:

示例在此

#mybox:after {
    /* Other properties.. */
    top: 50%;
    -webkit-transform: translate(0, -50%);
    transform: translate(0, -50%);
}

1
我在来这里询问之前尝试过使用 top:50%,但是无法使其正常工作。不管怎样,这是一个很棒的解决方案。非常感谢你。 - TNK

2

0

在编程中,在 div 元素之前显示箭头可以通过两种方式完成,你可以创建两个 div 元素,或者你可以使用 :before:after 与 div 元素一起使用。

以此例为例:

.arrow-up {
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid #f3f300;
  margin-left: 60px;
  transform: translateX(-50%);
  -webkit-transform: translate(-50%);
}

.big-reward {
  background-color: #faf300;
  padding: 10px;
  text-align: justify;
  width: 100px;
  margin-left: 0;
  color: #e21111;
}
<div>
  $452
</div>
<div class="arrow-up"></div>
<div class="big-reward" id="mybox"><span><strong>Big Reward!</strong> Here is a sample text.</span></div>

嘿,还要检查这个jsfiddle链接

参考:W3CodeSchool.com


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