Div根据div中的跨度调整大小

时间:2017-05-18 01:59:02

标签: html css

我在div标签内有一个span,如下所示

<div class="Panel">
<span class="spanClass">
This is a test </br> break added <br> second break
</span>
</div>

 .Panel {
    font-size: .7em;
    color: Black;
    font-family: Verdana, Arial, Sans-Serif;
    margin: 5px 0px 5px 0px;
    padding: 5px 50px 5px 50px;
    border: solid 1px black;
    background-color: yellow;
    text-align: center;
    vertical-align: middle;
    height: auto;
  text-align: left;
  min-width:200px
  width:auto;
  }

  .spanClass
  {
    background-color: red;
    width:auto;
  }

演示:https://jsfiddle.net/2k0rq3q0/4/

我希望div根据span中的文本调整大小,而不是取父级的宽度。这可能吗? 我可以设置最大宽度:200px;但是我想按照文字调整大小。

另外,如果跨度中没有文本,是否可以不显示div?现在,显示空框

4 个答案:

答案 0 :(得分:1)

.Panel设置为display:inline-block将其缩小到其内容。你仍然有填充,使它比内容更宽,但你也可以删除它。这是一个fiddle

.Panel {
    font-size: .7em;
    color: Black;
    font-family: Verdana, Arial, Sans-Serif;
    margin: 5px 0px 5px 0px;
    //padding: 5px 50px 5px 50px; <- remove the padding if you truly want it flush
    border: solid 1px black;
    background-color: yellow;
    text-align: center;
    // vertical-align: middle; <- not needed, it's for inline elements and table cells
    // height: auto; <- not really needed, unless it's inheriting a height elsewhere
    text-align: left;
    min-width:200px
    // width:auto; <- not really needed, unless it's inheriting a width elsewhere
}

答案 1 :(得分:1)

请查看以下示例。只需添加display:inline-block;将解决您的问题

 .Panel {
	font-size: .7em;
	color: Black;
	font-family: Verdana, Arial, Sans-Serif;
	margin: 5px 0px 5px 0px;
	padding: 5px 50px 5px 50px;
	border: solid 1px black;
	background-color: yellow;
	text-align: center;
	vertical-align: middle;
	height: auto;
  text-align: left;
  min-width:100px;
  width:auto;
  display: inline-block;
  }
  
  .spanClass
  {
    background-color: red;
    width:auto;
  }
<div class="Panel">
<span class="spanClass">
This is a test test test test test test test test test test </br> break added <br> second break
</span>
</div>

答案 2 :(得分:0)

使用覆盖

<div class="Panel panel2">
<span class="spanClass ">
This is a test test test test test test test test test test </br> break added <br> second break
</span>
</div>

for css

 .panel2{
        font-size: 2em !important;
  }

答案 3 :(得分:0)

您可以使用脚本

轻松完成此操作
$(document).ready(function(){
    $('.Panel').width($('.spanClass').width()); 
});

fiddle here