【问题标题】:inexplicable space inside divdiv里面莫名其妙的空间
【发布时间】:2014-06-30 22:58:00
【问题描述】:

我正在尝试为我的页面制作一个分隔符,使用三个不同颜色的 div 来形成一条高度为 2px 的单行。我正在创建一个包含 3 个细分的 div,每个细分的高度为 2 px。父 div 莫名其妙地占用了 18px 的空间,我认为父 div 应该只占用他孩子的空间。

这是我的 HTML 代码:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body style="margin: 0; padding: 0">
    <div class="separator">
        <span class="third t1"></span><!--
        --><div class="third t2"></div><!--
        --><div class="third t3"></div>
    </div>      
</body>
</html>

还有我的 CSS:

.separator {
    height: 2px;
    width: 100%;        
}   

.third {
    height: 2px;
    margin-top: -10px;
    width: 33.33%;
    display: inline-block;
}

.t1 {
    background-color: #ff7474;  
}

.t2 {
    background-color: #f1f58d;  
}

.t3 {
    background-color: #72baf1;  
}

这是我的代码的 codepen.io 链接:

http://codepen.io/anon/pen/vjdnx

【问题讨论】:

  • 示例小提琴?此外,根据displayposition,div 通常会占用 100% 的可用宽度。

标签: html css


【解决方案1】:

您的问题是,因为您使用的是内联块,所以分隔符 div 使用字体大小来确定它的高度和子元素的行高。

首先你需要注释掉所有的空格(display:inline-block 会将元素视为句子中的单词,因此它们之间会出现空格):

<div class="separator"><!--
    --><span class="third t1"></span><!--
    --><div class="third t2"></div><!--
    --><div class="third t3"></div><!--
--></div>    

那么你需要在你的分隔符 div 中添加以下样式:

.separator {
    height: 2px;
    width: 100%;    
    font-size:2px;
}   

Example

【讨论】:

  • 谢谢,我不会考虑字体大小。你先生是我的英雄!
【解决方案2】:

JsFiddle

只需将float:left; 添加到.third 类。这是摆脱display:inline-block 创建的空间的一种方法。我还删除了margin-top:-10px(否则你看不到元素)

之前

.third {
   height: 2px;
   margin-top: -10px;
   width: 33.33%;
   display: inline-block;
}

之后

.third {
   float:left;
   height: 2px;
   width: 33.33%;
   display: inline-block;
}

记住:浮动元素需要一个带有overflow:hidden 的父元素或一个带有clear:both 的元素。

【讨论】:

  • 我在这家公司实习的主管强烈禁止我使用花车,他说我不应该使用这些。
  • @Radu 不要让自己被你的主管愚弄。如果您知道如何使用浮点数,则它们有其用例。这是一篇关于该主题的好文章:alistapart.com/article/css-floats-101
  • 我引用耀西的话。花车不是邪恶的。顺便说一句好文章
猜你喜欢
  • 2012-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 2012-03-12
  • 2019-02-04
  • 2013-07-07
  • 2013-04-22
相关资源
最近更新 更多