CSS:添加边框会更改背景颜色(?!) [英] CSS: Adding a border changes the background-color (?!)

查看:235
本文介绍了CSS:添加边框会更改背景颜色(?!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML:

<div> <p></p> </div> 

CSS:

div { background-color:green; border-top:1px solid white; }
p { background-color:yellow; height:50px; margin:70px; } 

演示: http://www.jsfiddle.net/Xy8QF/4/

为什么黄色区域上面的区域绿色,区域下面是白色?

Why is the area above the yellow paragraph green, and the area bellow it white?

btw我已经想出了这一点,但我想我还是会发布。考虑一个谜语:)

btw I already figured this out, but I thought I'll post this anyway. Consider it a riddle :)

只需添加到接受的答案:

Update: Just to add to the accepted answer:


  1. 只有垂直边距折叠

  2. 如果外部元素(在本例中为DIV)具有填充或边框,则边距不会折叠


推荐答案

这是因为 position:static (默认值)的两个块元素的边距根据 CSS 2.1 8.3.1 ,即边距被转移到正文元素。此演示说明绝对定位的元素不会发生这种情况,例外情况之一(以及a < - 边框)。

This happens because the margins of two block elements with position:static (the default) collapse as per CSS 2.1 8.3.1, i.e. the margin is "carried over" to the body element. This demo shows it does not happen with absolutely positioned elements, one of the exceptions (along with a non-none border) listed in the aforementioned standard.

这篇关于CSS:添加边框会更改背景颜色(?!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆