.wrapper {
outline: 1px solid blue;
padding: 40px;
}
.content {
outline: 1px solid red;
background-color: #D8D8D8;
}
.content p {
outline: 1px dotted blue;
background-color: rgba(255, 255, 0, 0.3);
margin: 0 0 0 0;
text-align: justify;
}
.content p.lefty {
margin-left: -20px;
}
.content p.righty {
margin-right: -20px;
}
<div class="wrapper">
<div class="content">
<p>Lorem ipsum dolor sit amet, ...</p>
<p class="lefty">Sed ipsum ante, dictum vel rhoncus id, ...</p>
<p class="righty">Curabitur aliquam tristique mattis...</p>
</div>
</div>
和
标签添加了outline
,以显示内容框的范围。
第一个段落没有边距,我将其中一个段落向左偏移,另一个段落向右偏移。
如果您有足够的内容来填满段落的宽度(或者显示轮廓),则会看到文本框流出content
框。您还可以从段落的outline
中看到,文本确实向左和向右延伸。
但是,要看到右侧的效果,您需要足够的内容来填满段落的整个宽度,或者需要在子元素上设置背景颜色或轮廓。
如果您开始修复content
的宽度和高度,则会看到其他效果,例如段落超出content
。
研究这个简单的代码结构可以说明CSS盒模型的许多方面,并且花一些时间进行研究非常有益。
Fiddle参考:http://jsfiddle.net/audetwebdesign/2SKjM/
如果您从中删除填充,则可能无法注意到右边距的移动,因为元素将向外扩展以填充父容器或页面宽度,具体取决于HTML/CSS的特定细节。
为什么我的示例没有显示效果!!!???
在您的示例中,您没有看到效果,是因为通过指定width:100%
,您固定了
元素的宽度,这会使段落占据父容器的宽度(在您的示例中为200像素)。
如果您将宽度从100%
更改为auto
:
p {
background: blue;
width: auto;
}
您会看到第二段落就像您期望的那样向右移动。
注意:轮廓线与边框 另外,请注意红框是由于outline
而产生的,它将文本框包围在content
内部,即使文本框超出父级(content
)元素。 因此,outline
框可以比相应元素的border
框大得多。
width_of_containment_element + 20
,因此它将比包含元素的宽度更大。我只是想知道为什么 margin-left 会将元素从父元素中拉出来,但 margin-right 却不会。 - anton_byrnawidth: auto
- inorganik.something > * { max-width: 100% }
破坏了负右边距,因此使用.something > .special { max-width: initial }
覆盖它对我有用。 - JamesWilsonwidth:auto;
实现成功的人,请尝试max-width: none
。 - Maxim Pokrovskii