CSS3 三角形在 div 之前



我试图使用 css 在div 之前添加一个三角形,但它最终在它下面。

http://jsfiddle.net/lasseedsvik/LwE7u/

.HTML

<div id="container">
1234   
<div id="toolbar">
Want silly triangle before this div to left
</div>    
</div>

.CSS

#container {
width: 500px;
}
#toolbar:before
{
width: 44px;
content: '';
height: 0px;
border-style: solid;
border-width: 0 0 44px 44px;
border-color: transparent transparent blue transparent;
}
#toolbar {
float: right;
width: 350px;
height: 44px;
background: blue;
color: #fff;
}

是否缺少显示之类的东西:内联或其他东西?

使用CSS 定位正确设置三角形,在下面的示例中,我在父元素上使用position: relative;,而不是对:before伪元素使用position: absolute;。并且比使用left属性,这是元素的dobulewidth

始终,您应该用定位relative的容器包裹absolute定位的元素,否则您的元素将在野外飞出。

演示

#container {
width: 500px;
}
#toolbar:before {
position: absolute;
left: -88px; /* Double the element size */
width: 44px;
content: '';
height: 0px;
border-style: solid;
border-width: 0 0 44px 44px;
border-color: transparent transparent blue transparent;
}
#toolbar {
float: right;
width: 350px;
height: 44px;
background: blue;
color: #fff;
position: relative;
}

注意:通常,当您使用 CSS 创建三角形时,它是一个 将元素设置为heightwidth的常见做法是0,如果 你想要,只需调整它们。

尝试将div#工具栏放在position:relative中,并以绝对方式定位伪元素。然后调整位置和边距以正确定位。

http://jsfiddle.net/LwE7u/2/

最新更新