我在尝试将一段文本置于灰色框内时遇到问题,每次我移动文本时整个灰色框都会移动。我似乎无法弄清楚这一点。问题出在“show-collections-box”和其中的收藏文本链接上。感谢您的帮助。
编辑:所以我制作了一个 div id="show-collections-box"
,它创建了一个 228px x 50px 的灰色框。在 div
中我有一个链接,我用 class="margin"
将链接包装在另一个 div
标签中。当我应用边距类时,不是只将 div class="margin"
内的链接向下移动,而是整个灰色框 div id="show-collections-box"
,加上链接向下移动了 20px。
这是它的一个 jsfiddle,您可以看到 20px margin-top
将整个灰色框向下推 20px 而不仅仅是“集合”一词。
HTML
<div id="show-collections-box">
<div class="margin"><a href="www.example.com">Collections</a></div>
</div>
CSS
#show-collections-box {
border-bottom: solid 1px #ececec;
border-left: solid 1px #ececec;
background: #faf9f9;
width: 228px;
height: 50px;
}
.margin {
margin-top: 20px;
}
最佳答案
我不确定我是否确切知道您的具体问题可能是什么,因此此答案仅基于目前发布的有限信息。
...every time I move the text the entire grey box moves.
听起来您可能对如何将边距和填充应用于元素感到困惑。
如果您将 margin
应用于 div
,则该边距位于 div
的外部,从而在页面上四处移动.边距不应用于div
的内容。
如果您将 padding
应用于 div
,则该填充位于 div
的边界内,从而将其内容推离div
的边界。填充不应用于div
的内容。
The problem is with the "show-collections-box" and the link to the collection text inside it.
你没有解释问题是什么。一旦您对您想要实现的目标提供了更详细的解释,我将相应地编辑此答案。
编辑:
我相信可能有更好的方法来实现您的目标,但为了回答您的具体问题,我所做的就是完全删除内部 div
并将 20 像素作为顶部填充添加到外部 分区
。 (应该注意的是,填充将添加到div
的大小。即,一个 50 像素高的 div
和 20 像素的顶部填充最终将达到 70 像素高)
编辑 2:
如果只有一行文本不会换行并且您知道div
的高度,只需添加一个line-height
等于 div
的高度。文本将始终垂直居中。
关于css - HTML/CSS : margin and padding values keep applying to entire div instead of just the text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7629738/