将div-width减小到其内容宽度或上/下的内容宽度

时间:2014-03-13 21:09:40

标签: html css

如果你看看这个jsfiddle:

http://jsfiddle.net/v5GXT/1/

<div class="text">
    <div id="image">this is an image with unknown width</div>
    This is some text above,This is some text above,This is some text above,This is some text above,This is some text above,This is some text above,
    <div class="code">special content</div>
    and this is some text below,and this is some text below,and this is some text below,and this is some text below,and this is some text below,
</div>

的CSS:

.text{
    color:red;
    text-align:justify;
    margin-top:20px;
}

.code{
    border:1px solid blue;
    border-left:10px solid #ccc;
    background:#eee;
    padding:5px;
    margin:5px;
}
.code:before{
    display:block;
    font-size:80%;
    font-style:italic;
    content:"Example:";
    margin-bottom:5px;
}

#image{
    float:right;
    border:2px solid red;
    height:150px;
    width:150px;
    margin-left:40px;
}

我希望蓝色div框(特殊内容)与上/下文本的宽度相同,或者内容的宽度,无论哪种更容易。为什么这个div就像屏幕一样宽?

任何建议最好的方法是什么?





EDIT1: 溢出的简易解决方案: http://jsfiddle.net/v5GXT/6/

.code{
    border:1px solid blue;
    border-left:10px solid #ccc;
    background:#eee;
    padding:5px;
    margin:5px;
    overflow-x: hidden;
}

3 个答案:

答案 0 :(得分:1)

  

我希望蓝色div框(特殊内容)的宽度与   上/下文字

您可以将overflow-x: hidden;添加到.code div元素以隐藏水平溢出,如下所示:

.code {
    border:1px solid blue;
    border-left:10px solid #ccc;
    background:#eee;
    padding:5px; margin:5px;

    overflow-x: hidden;
}

<强> WORKING DEMO

答案 1 :(得分:1)

有很多不同的方法,这是最简单的方法之一:

.code包含在阻止级别div中,并使.code成为inline-block

HTML:

<div class="codeContainer">
    <div class="code">special content</div>
</div>

CSS:

.codeContainer {
    display: block;
}

.code {
    display:inline-block;
    width:auto;
    border:1px solid blue;
    border-left:10px solid #ccc;
    background:#eee;
    padding:5px;
    margin:5px;
}

DEMO: http://jsfiddle.net/v5GXT/13/

答案 2 :(得分:0)

检查此fiddle

css change

.code{
margin: 5px 190px 0 0;
}