如何防止DIV展开以占用所有可用的宽度? [英] How do I keep a DIV from expanding to take up all available width?

查看:151
本文介绍了如何防止DIV展开以占用所有可用的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的HTML中,我希望图像周围的框架贴合,而不是拉伸,并占用父容器中的所有可用宽度。我知道有几种方法可以做到这一点(包括手动设置其宽度为特定数量的像素的可怕的事情),但什么是方式?



编辑:一个答案建议我关闭display:block - 但是这会导致渲染在我测试过的每个浏览器中都出现格式错误。

编辑:如果我在display:block中添加float:left画框和清楚:两者到P标签,它看起来不错。但我不总是希望这些框架浮在左边。是否有更直接的方式来完成任何float操作?



  .pictureframe {display:block; margin:5px; padding:5px; border:solid brown 2px; background-color:#ffeecc;}#foo {border:solid blue 2px; float:left;} img {display:block;}  

  < div id =foo> < span class =pictureframe> < img alt =''src =http://stackoverflow.com/favicon.ico/> < / span> < p>为什么米色矩形这么宽? < / p>< / div>  

解决方案

方式是使用:

  .pictureframe {
display:inline-block;
}

但是,Firefox 2.x不支持此功能,因此您可能需要使用解决方法,例如使用 display:table 代替该浏览器:

  .pictureframe {
display:table;
display:inline-block;
}

将其设置为表格有一些缺点,具体取决于您的情况, code> table-cell 可能更合适。



编辑:浮动元素效果相同,这是因为浮动元素使用相同的缩小-to-fit 算法来确定宽度。


In the following HTML, I'd like the frame around the image to be snug -- not to stretch out and take up all the available width in the parent container. I know there are a couple of ways to do this (including horrible things like manually setting its width to a particular number of pixels), but what is the right way?

Edit: One answer suggests I turn off "display:block" -- but this causes the rendering to look malformed in every browser I've tested it in. Is there a way to get a nice-looking rendering with "display:block" off?

Edit: If I add "float: left" to the pictureframe and "clear:both" to the P tag, it looks great. But I don't always want these frames floated to the left. Is there a more direct way to accomplish whatever "float" is doing?

.pictureframe {
  display: block;
  margin: 5px;
  padding: 5px;
  border: solid brown 2px;
  background-color: #ffeecc;
}
#foo {
  border: solid blue 2px;
  float: left;
}
img {
  display: block;
}

<div id="foo">
  <span class="pictureframe">
       <img alt=''
        src="http://stackoverflow.com/favicon.ico" />
  </span>
  <p>
    Why is the beige rectangle so wide?
  </p>
</div>

解决方案

The right way is to use:

.pictureframe {
    display: inline-block;
}

However, Firefox 2.x doesn't support this, so you may need to use a workaround, such as using display: table instead for that browser:

.pictureframe {
    display: table;
    display: inline-block;
}

Setting it to be a table has some drawbacks, depending on your situation, table-cell may be more appropriate.

Edit: Floating the element also produces the same effect, this is because floating elements use the same shrink-to-fit algorithm for determining the width.

这篇关于如何防止DIV展开以占用所有可用的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆