我遇到了基本CSS的问题。容器在其中包含图像时移动

时间:2017-09-27 04:04:04

标签: css

<html>
<head>
<style>
    <!-- * {
    box-sizing: border-box;
    } -->

    div {
        width: 50%;
        margin: auto;
    }

    .cardBox {
        display: inline-block;
        border: solid 1px black;
        height: 102px;
        width: 68px;
        margin: 100px 0px 0px 0px;
        padding: 0px;
    }

    span img {
        height: 100%;
        width: 100%;
    }
</style>
</head>
<body>
    <div>
        <span class="cardBox" id="box1"><img src="h4.png"></span>
        <span class="cardBox" id="box2"><img src="h4.png"></span>
        <span class="cardBox" id="box3"><img src="h4.png"></span>
        <span class="cardBox" id="box4"></span>
        <span class="cardBox" id="box5"></span>
    </div>
</body>
</html>

Chrome和FF中的结果相同。我试图设置图像高度/宽度以匹配跨度cardBox,我也尝试了不到100%。我也试过了auto。这一切都导致容器跨度的各种运动。图像本身是99x66px,下面是它的副本:

enter image description here

我遇到的另一个问题是为什么他们之间存在间隙?

2 个答案:

答案 0 :(得分:1)

inline-block存在一些问题。将其更改为inline-flex并完美地运作。

以下是摘录。

&#13;
&#13;
div {
  width: 50%;
  margin: auto;
}

.cardBox {
  display: inline-flex;
  border: solid 1px black;
  height: 102px;
  width: 68px;
  margin: 100px 0px 0px 0px;
  padding: 0px;
}

span img {
  height: 100%;
  width: 100%;
}
&#13;
<div>
  <span class="cardBox" id="box1"><img src="https://i.stack.imgur.com/1MfOn.png"></span>
  <span class="cardBox" id="box2"><img src="https://i.stack.imgur.com/1MfOn.png"></span>
  <span class="cardBox" id="box3"><img src="https://i.stack.imgur.com/1MfOn.png"></span>
  <span class="cardBox" id="box4"></span>
  <span class="cardBox" id="box5"></span>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

好吧,只需将display: block添加到范围中的img(代码如下) 第二个,display: inline-block创建margin-right值= 4px(我不记得为什么会这样,可能需要稍后谷歌),所以有两种方法来解决它< / p>

  1. 使用float: left代替display: inline-block
  2. 或将margin-right: -4px添加到cardBox
  3. &#13;
    &#13;
    <!-- * {
    box-sizing: border-box;
    } -->
    
    div {
        width: 50%;
        margin: auto;
    }
    
    .cardBox {
        /*display: inline-block;*/
        border: solid 1px black;
        height: 102px;
        width: 68px;
        margin: 100px 0px 0px 0px;
        padding: 0px;
        float: left;
    }
    
    span img {
        height: 100%;
        width: 100%;
        display: block;
    }
    &#13;
     <div>
            <span class="cardBox" id="box1"><img src="http://www.placehold.it/99x66"></span>
            <span class="cardBox" id="box2"></span>
            <span class="cardBox" id="box3"><img src="http://www.placehold.it/99x66"></span>
            <span class="cardBox" id="box4"></span>
            <span class="cardBox" id="box5"></span>
        </div>
    &#13;
    &#13;
    &#13;