Why add block level to pseudo-element?

守給你的承諾、 提交于 2019-12-12 10:01:01

问题


From code on this page: http://css-tricks.com/snippets/css/sticky-footer/

.page-wrap {
  min-height: 100%;
  /* equal to footer height */
  margin-bottom: -142px; 
}
.page-wrap:after {
  content: "";
  display: block;
}

Can anyone explain what the .page-wrap:after block is doing? I understand the after pseudo-element but I don't understand what is happening here.


回答1:


Check out when you edit the Codepen demo and remove either .page-wrap:after from the line which sets its height or its display: block property. Then click 'Add content'. Because .page-wrap has a negative margin-bottom, it will only push the footer down 142 pixels too late and let the text overflow. So in short, it fills the negative bottom margin... Yes, you could probably do the same by using a simple div with relative positioning, z-indexing etc. Actually tested it & adding a block element after .page-wrap, like this works too:

.fix {
  position: relative;
  display: block;
  z-index: -2;
  bottom: 0;
  height: 142px;
  width: 100%;
}

But while HTML5 & CSS3 are there, why not use that.. And hey, you don't have to create a new element, simply set it from CSS.. How awesome is that!

Other more & more popular uses of the :after prefix (I saw some in WP themes) include using it as a replacement for clearfix divs. Check out this article for further reading: http://css-tricks.com/snippets/css/clear-fix/

You might wonder why he set the negative bottom margin in the first place; Answer: because he wanted the .page-wrap {min-height: 100% } not to push the footer under the fold on page load, IF the content doesn't extend any further. Percentage heights would have eliminated the need of any of these tricks, eg footer height 10%, page-wrap min-height 90%, but have the disadvantage that you can't control the exact footer height...



来源:https://stackoverflow.com/questions/23399396/why-add-block-level-to-pseudo-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!