关于在div中包装文本的建议

时间:2013-11-19 14:04:56

标签: html css

我正在创建一个联系人卡片样式的布局,旁边有一张照片和文字,如下所示:

http://jsfiddle.net/L7pWv/5/

HTML:

<div class="container">
    <div class="contact-card">
        <div class="photo"></div>

        <div class="details">
            <span class="name">My Name</span>
            <span class="description">This is some really long text that should wrap nicely when things all work OK</span>
        </div>

        <div class="clearfix"></div>
    </div>    

    <div class="contact-card">
        <div class="photo"></div>

        <div class="details">
            <span class="name">My Name 2</span>
            <span class="description">Short description</span>
        </div>

        <div class="clearfix"></div>
    </div>
</div>

CSS:

.container {    
    width: 350px;
}

.contact-card {
    background-color: whitesmoke;
    border-bottom: 1px solid #ddd; 
    white-space: nowrap;
}

.contact-card .photo {
    float: left;
    width: 80px;
    height: 50px;
    background-color: tan;
    margin: 10px;
}

.contact-card .details {
    display: inline-block;
    margin: 10px 0;
}

.contact-card .name {
    display: block; 
    font-weight: bold; 
    line-height: 1em;
}

.contact-card .description {
    display: block; 
    font-size: 0.8em; 
    color: silver; 
    line-height: 1em;
    white-space: normal;
}

.clearfix {
    clear: both;
}

正如你可以看到的那样,当文字非常长时,它会根据我的白色空间设置最终进行包裹,但在此之前它会超过联系人卡片的大小。我可以在“描述”类上放置一个90px的右边距,以保持文本在边界内(有效),但我不禁觉得这是错误的。我希望它能够自然地保持在其父母的范围内,但却无法想到实现这一目标的最佳方式。有什么想法吗?

4 个答案:

答案 0 :(得分:2)

考虑进行这些更改:

.contact-card {
    display: inline-block;
}

.contact-card .details {
    display: block; 
}

这将使每张卡显示为内联,同时保持卡内的文本不会指定边距。

答案 1 :(得分:1)

有点棘手,因为我不知道你会用什么用它,但我可能会做这些改变。

摆脱

 <div class="clearfix"></div>

如果您进行简单的添加,则不需要:

.contact-card {
    float:left;
}

然后将.contact-card .details更改为:

.contact-card .details {
    padding: 10px 0;
}

这应该会为您提供您所追求的"The width of the details element should really be dictated by the parent."行为

http://jsfiddle.net/L7pWv/6/

答案 2 :(得分:0)

CSS:

.contact-card .details {
   display: inline-block;
   margin: 10px 0;
   width:70%;

}

小提琴:http://jsfiddle.net/L7pWv/2/

答案 3 :(得分:0)

我建议您不要使用inline-block。您不希望.detail元素溢出它的父元素。因为您已经浮动了照片,所以您可以将元素放在照片元素旁边。

请注意,当您需要元素中的空格时,应使用填充,并在需要元素之外时使用边距。

当您将照片浮动时,无需white-space: nowrap;

<强> jsFiddle

我唯一改变的是使用填充和边距并删除了white-space