div未居中后向下箭头

时间:2014-01-28 18:40:15

标签: css html

我刚刚做了div

Demo

但是,div之后的箭头不是居中对齐,一旦我在里面插入了新的div

HTML

<div id="hero_intro">
    <div class="quote">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
</div>

CSS

#hero_intro {
    background: #f18c22;
    height: 150px;
    text-align: center;
    color:#fff;
    z-index: 5000;
    font-size: 32px;
}
#hero_intro:after {
    content:'';
    position: absolute;
    width: 0;
    height: 0;
    margin-top: 150px;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-top: 20px solid #f18c22;
}
#hero_intro .quote {
    width: 80%;
    margin-top: 30px;
    display: inline-block;
    text-align: center;
    line-height: 1.2em;
    color:#fff;
}

3 个答案:

答案 0 :(得分:2)

left: 50%;添加到#hero_intro:after css。父容器显然必须是position: relative

答案 1 :(得分:2)

left: 50%;设为中心但不准确居中,因此请使用margin-left: -20px;,即width定位三角形的absolute总数的1/2。

Demo

#hero_intro:after {
  content: '';
  position: absolute;
  width: 0; 
  height: 0; 
  margin-top: 150px;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #f18c22;
  left: 50%; /*Add these*/
  margin-left: -20px;
}
  

注意:请确保对父容器使用position: relative;,然后相应地使用position元素。还要使用bottom属性而不是margin-top

更好的解决方案,无论您的元素是height,都要摆脱margin-top并将position: relative;分配给父容器。

Demo 2

#hero_intro {
    background: #f18c22;
    height: 150px;
    text-align: center;
    color:#fff;
    z-index: 5000;
    font-size: 32px;
    position: relative;
}
#hero_intro:after {
    content:'';
    position: absolute;
    width: 0;
    height: 0;
    bottom: -20px;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-top: 20px solid #f18c22;
    left: 50%;
    margin-left: -20px;
}
#hero_intro .quote {
    width: 80%;
    margin-top: 30px;
    display: inline-block;
    text-align: center;
    line-height: 1.2em;
    color:#fff;
}

答案 2 :(得分:0)

这是修复:http://jsfiddle.net/K5qdc/3/

#hero_intro{
background: #f18c22 ;
height: 150px;
text-align: center;
color:#fff;
z-index: 5000;
font-size: 32px; }

#hero_intro:after { 
content: '';  
position: absolute;
width: 0; 
height: 0; 
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 20px solid #f18c22;
bottom: 28px;
left:0;
margin: 0 auto;
right:0; }

其余的你可以在fiddler中找到它