CSS3:keep:after和:before元素与元素高度对齐

时间:2012-07-04 14:50:30

标签: css css3 pseudo-element

我有一个带头设计的大头颅:

enter image description here

此处演示:http://jsfiddle.net/uGECm/

我们的想法是使用“包裹”元素的灰色标签;然而,标签的高度是未知的(它可以根据其内容而变化) - 我的问题是如果标签改变大小,那么像三角形这样的2个伪元素会得到错误的位置,这就是因为它们的位置是相对的。

有什么想法吗?

ps:我正在寻找一个no-js和无图像解决方案。

3 个答案:

答案 0 :(得分:3)

section h2:before, section h2:after {
    width: 0;
    height: 0;
    display: block;
    position: absolute;
    bottom: 0;
    margin: 0 0 -10px 0;
}

section h2:before {
    content: '\0000a0';
    border-left: 10px solid transparent;
    border-top: 10px solid #323232;
}

section h2:after {
    content: '\0000a0';
    border-right: 10px solid transparent;
    border-top: 10px solid #323232;
    right: 0;
}​

这是一个包含更多CSS格式的分支:http://jsfiddle.net/bqXeJ/

值得一看风格指南like the one I wrote here,如果你使用Lea Verou的prefixfree.js,你可以跳过为每个浏览器供应商编写声明。

答案 1 :(得分:1)

您可以绝对定位伪元素。由于section h2position: relative,将它们设置为top: 100%会使它们停留在底部,无论父母的大小如何:

section h2:before, section h2:after {
  position: absolute;
  top: 100%;
}

答案 2 :(得分:1)

  • 使用绝对而非相对位置:before和:after
  • bottom:-10px;应用于
  • 分别应用left:0;right:0;
  • 取下浮球。浮动对具有绝对位置的元素没有影响。

更新了jsfiddle demo

section h2:before,
section h2:after {
    content: '\0000a0';
    width: 0;
    height: 0;
    position: absolute;    
    bottom: -10px;
    display: block;
}
section h2:before {
    border-left: 10px solid transparent;
    border-top: 10px solid #323232;
    left: 0;
}
section h2:after {
    border-right: 10px solid transparent;
    border-top: 10px solid #323232;
    right: 0;
}