微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何清除在使用CSS定位元素后出现的空格

我一直在寻找这个问题,并最终找到解决方案在一些晦涩的论坛在第10页的谷歌。解决方案是在答案

出现以下问题:
经过相对定位后,CSS的元素就会得到一个元素的空格,我不想要空格!

.thetext 
    {
        width:400px;
        background:yellow;
        border: 1px dashed red;
        margin:50px;
        padding:5px;
        font-weight:bold;
    }
    .whiteblob
    {
        position:relative;
        top:-140px;
        left:70px;
        width:200px;
        height:50px;
        border: 4px solid green;
        background:white;
        font-size:2.5em;
        color:red;
        
    }
    .footerallowedwhitespaceinblue
    {
        height:10px;
        background-color:blue;
    }
    .footer
    {
        background-color:grey;
        height:200px;
    }
<div class="thetext"><script type="text/javascript">for(c=0;c<50;c++){document.write("Lorem ipsum dolor est,");}</script>
    </div>
    <div class="whiteblob">
        &nbsp;buy this!
    </div>
    <div class="footerallowedwhitespaceinblue">
    </div>
    <div class="footer">
        The whitespace above is way to big! The buy this still takes up space whilst it is moved.
    </div>

JSfiddlehttp://jsfiddle.net/qqXQn/

正如您可以在示例中看到的,我想要的唯一的空格是由文本块引起的空格,边距为50px;并且由蓝色的蓝色空白(蓝色,因此可见)。
问题是…现在的空白太大,因为“购买这个”div在相对定位之后仍然占据空间。

我如何解决这个问题?

解决方法

您可以通过应用等于元素的宽度或高度的负边距来简单地解决此问题。

对于位于顶部的100px高度的元素,您将应用margin-bottom:-100px;

对于位于底部的100px高度的元素,您将应用margin-top:-100px;

对于位于左侧的100px宽度的元素,您将应用margin-right:-100px;

对于位于右侧的100px宽度的元素,您将应用margin-left:-100px;

切&粘贴css片段:

.top 
    {
    postion:relative;
    top:-100px;
    height:25px;
    margin-bottom:-25px;
    }
.bottom
    {
    postion:relative;
    top:100px;
    height:25px;
    margin-top:-25px;
    }
.left
    {
    postion:relative;
    left:-100px;
    width:25px;
    margin-right:-25px;
    }
.right
    {
    postion:relative;
    left:100px;
    width:25px;
    margin-left:-25px;
    }

然后,重做的示例代码变为:

.thetext 
{
    width:400px;
    background:yellow;
    border: 1px dashed red;
    margin:50px;
    padding:5px;
    font-weight:bold;
}
.whiteblob
{
    position:relative;
    top:-140px;
    left:70px;
    width:200px;
    height:50px;
    margin-bottom:-50px;
    border: 4px solid green;
    background:white;
    font-size:2.5em;
    color:red;
    
}
.footerallowedwhitespaceinblue
{
    height:10px;
    background-color:blue;
}
.footer
{
    background-color:grey;
    height:200px;
}
<div class="thetext"><script type="text/javascript">for(c=0;c<50;c++){document.write("Lorem ipsum dolor est,");}</script>
</div>
<div class="whiteblob">
    &nbsp;buy this!
</div>
<div class="footerallowedwhitespaceinblue">
</div>
<div class="footer">
</div>

http://jsfiddle.net/qqXQn/1/

原文地址:https://www.jb51.cc/css/219913.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。