【问题标题】:image with border inside fixed width container固定宽度容器内带有边框的图像
【发布时间】:2017-11-15 20:37:25
【问题描述】:

我有一个固定宽度的容器 (div) 和一个里面的图像,这个图像应该适合容器宽度但有一个边距,像这样:

我尝试为容器添加填充,它使容器变大。

我的第二次尝试是为图像添加边距,但这使它超出了容器。

两次尝试都在这个sn-p中:

$('.result1').html('div is ' + $('.test1').width() + ' and image is ' + $('.test1 img').width());
$('.result2').html('div is ' + $('.test2').width() + ' and image is ' + $('.test2 img').width());
div{
  width: 300px;
  background-color: #999;
}
img{
  background-color: #FFF;
  width: 100%;
}
.test1{
  padding:10px;
}
.test2 img{
  margin:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test1'>
  <img src='http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png' />
</div>
<div class='result1'></div>
<div class='test2'>
  <img src='http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png' />
</div>
<div class='result2'></div>

【问题讨论】:

    标签: css image containers margin padding


    【解决方案1】:

    希望我能理解您的问题。 您需要先删除添加到图像的边距。 比给你的 div 容器填充,还要给它添加 box-sizing:border-box-

    $('.result1').html('div is ' + $('.test1').width() + ' and image is ' + $('.test1 img').width());
    div{
      width: 300px;
      background-color: #999;
      box-sizing: border-box;
      padding: 10px;
    }
    img{
      background-color: #FFF;
      width: 100%;
    }
    .test1{
      padding:10px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class='test1'>
      <img src='http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png' />
    </div>
    <div class='result1'></div>
    <div class='test2'>
      <img src='http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png' />
    </div>
    <div class='result2'></div>

    让我知道它是否有效

    【讨论】:

    • 是的,这就是我一直在寻找的,我总是避免使用填充,因为它们使我的设计比我想要的更大,使用边框框更容易。 @WizardCoder 的答案也是正确的,但我标记了这个,因为 sn-p 更容易理解:)
    • 很高兴我能帮上忙。祝你好运
    【解决方案2】:

    您需要将box-sizing: border-box; 分配给您的容器,然后使用您的填充解决方案。此 CSS 阻止填充添加到元素的大小。

    【讨论】:

      猜你喜欢
      • 2018-10-02
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      相关资源
      最近更新 更多