使用::before溢出父元素高度的伪元素
Pseudo element using ::before overflow's parent element height
Plunker 代码是 here。
我尝试创建一个对话泡泡,其顶角和底角与父元素的角相同。
伪元素道具是,
.callout::before {
box-sizing: border-box;
height: 100%;
content: "";
position: absolute;
right: -0.2em;
padding: 1em;
background: inherit;
border: inherit;
border-right: 0;
border-bottom: 0;
transform: rotate(45deg);
z-index: -1;
}
我认为问题是,
1) 伪元素没有裁剪到父元素的高度
2) 伪元素并非完全来自父元素的右上角
看起来,
如何解决?
让我们假设父元素的高度为 x
。因为,您正在使用 ::before
元素通过将其旋转到 45deg
来显示箭头,箭头的对角线应等于父元素的高度。对角线的公式是side * sqrt(2)
。所以,
x = side * sqrt(2)
=> side = x / sqrt(2)
假设 x = 50
,那么 side
将是 35.35534
。因此,在您的 fiddle:
中应用相同的内容
div {
width: 100px;
height: 50px;
background: tomato;
position: relative;
}
div::before {
content: "";
display: block;
width: 35.35534px;
height: 35.35534px;
background: blue;
position: absolute;
transform: rotate(45deg);
transform-origin: 0 0;
left: 100%;
}
最好使用 css 预处理器,例如 SASS。这是我使用 sass 获得结果的代码。
Plunker 代码是 here。
我尝试创建一个对话泡泡,其顶角和底角与父元素的角相同。
伪元素道具是,
.callout::before {
box-sizing: border-box;
height: 100%;
content: "";
position: absolute;
right: -0.2em;
padding: 1em;
background: inherit;
border: inherit;
border-right: 0;
border-bottom: 0;
transform: rotate(45deg);
z-index: -1;
}
我认为问题是,
1) 伪元素没有裁剪到父元素的高度
2) 伪元素并非完全来自父元素的右上角
看起来,
如何解决?
让我们假设父元素的高度为 x
。因为,您正在使用 ::before
元素通过将其旋转到 45deg
来显示箭头,箭头的对角线应等于父元素的高度。对角线的公式是side * sqrt(2)
。所以,
x = side * sqrt(2)
=> side = x / sqrt(2)
假设 x = 50
,那么 side
将是 35.35534
。因此,在您的 fiddle:
div {
width: 100px;
height: 50px;
background: tomato;
position: relative;
}
div::before {
content: "";
display: block;
width: 35.35534px;
height: 35.35534px;
background: blue;
position: absolute;
transform: rotate(45deg);
transform-origin: 0 0;
left: 100%;
}
最好使用 css 预处理器,例如 SASS。这是我使用 sass 获得结果的代码。