before和after伪元素相对原来元素的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | <!DOCTYPE html> < html > < head > < meta charset = "UTF-8" /> < meta name = "viewport" content = "width=device-width, initial-scale=1.0" /> < meta http-equiv = "X-UA-Compatible" content = "ie=edge" /> < title >the Five-Starred Red Flag</ title > < style > .flag { width: 600px; height: 400px; background: red; margin: 100px auto; position: relative; } .stars { width: 0; height: 0; border-left: 57px solid transparent; border-right: 57px solid transparent; border-top: 42px solid yellow; position: absolute; top: 82px; left: 52px; } .stars::before, .stars::after { display: block; content: ""; width: 0; height: 0; border-left: 57px solid transparent; border-right: 57px solid transparent; border-top: 42px solid yellow; position: absolute; } .stars::before { /*left: -57px; top: -42px;*/ /*transform: rotate(-72deg);*/ } .stars::after { /*left: -65px; top: -40px;*/ /*transform: rotate(-143deg);*/ } .star-2 { transform: scale(0.33) rotate(20deg); left: 150px; top: 20px; } .star-3 { transform: scale(0.33) rotate(40deg); left: 190px; top: 60px; } .star-4 { transform: scale(0.33) rotate(60deg); left: 190px; top: 120px; } .star-5 { transform: scale(0.33) rotate(80deg); left: 150px; top: 160px; } </ style > </ head > < body > < div class = "flag" > < div class = "star-1 stars" ></ div > < div class = "star-2 stars" ></ div > < div class = "star-3 stars" ></ div > < div class = "star-4 stars" ></ div > < div class = "star-5 stars" ></ div > </ div > </ body > </ html > |
取消了line:38~40 以及 line:43~45的位置和旋转设置,可以看到如图,右下的三角形(before和after重合)左上角对齐stars元素的content盒子的左上角(在console中调试了一下stars的width和height来确认的)
为什么不是像文档流一样,伪元素(before和after)分别挨着star的上方和下方?
div的before和after伪元素的默认显示位置,究竟是如何规定的呢?
37
收起
正在回答
2回答
同学你好,首先很抱歉第一次没有理解同学的意思。
1、我们可以给四个边框都设置颜色看一下:
因为::before和::after添加的伪元素是作为stars的子元素,默认是从父元素内容的左上角开始显示的。
可以看出, 由于stars盒子宽高为0, 图片中四个边框的交点位置,就是内容的位置,所以显示的这两个伪类从内容位置开始显示,覆盖到边框上了。
2、又因为每个伪元素都设置了绝对定位,脱离了标准流不占位置,所以after就覆盖了before,可以将定位去掉再看一下:
如果我的回答帮助到了你,欢迎采纳,祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧