kir*_*rby 30 css position margin
我想设置元素position
来absolute
和有一个margin-bottom
,但似乎margin-bottom
没有效果.
HTML:
<div id='container'></div>
Run Code Online (Sandbox Code Playgroud)
CSS:
#container {
border: 1px solid red;
position: absolute;
top: 0px;
right: 0px;
width: 300px;
margin-bottom: 50px; // this line isn't working
}
Run Code Online (Sandbox Code Playgroud)
小智 39
我知道这不是一个非常及时的答案,但有一种方法可以解决这个问题.您可以在元素内部添加"spacer"元素absolute
,其中底部边距为负,高度与负底边距相同.
HTML:
<div id="container">
<div class="spacer"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
// same container code, but you should remove the margin-bottom as it has no effect
// spacer code, made it a class as you may need to use it often
.spacer {
height: 50px;
margin: 0 0 -50px 0;
/* margin: 20px 0 -50px 0; use this if you want #container to have a 'bottom padding', in this case of 20px */
background: transparent; /* you'll need this if #container's parent element has a different background from #container itself */
}
Run Code Online (Sandbox Code Playgroud)
nik*_*nik 25
基于Joey的回答,为了获得更清晰的标记,请使用CSS :after
-selector为所需的底部边距添加间隔.
#container:after {
position: absolute;
content: "";
bottom: -40px;
height: 40px;
width: 1px;
}
Run Code Online (Sandbox Code Playgroud)
Nie*_*sol 16
margin-bottom
当您的元素位于其顶部时,您期望做什么?
margin-bottom
absolute
如果元素没有top
属性,它将只对ly-located元素执行任何操作.
小智 6
您需要将 设为position
才能relative
设置其margin
。
当元素位于 中时,margin-bottom
,和将不起作用。margin-left
margin-right
position: absolute
示例:HTML:
<img src="whatever.png"/>
Run Code Online (Sandbox Code Playgroud)
CSS:
img {
position: relative;
margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)