【问题标题】:Image 100% below the img's original width图片比 img 的原始宽度低 100%
【发布时间】:2015-03-05 18:14:57
【问题描述】:

我正在尝试将其容器的img 宽度设置为100%,容器根据屏幕宽度更改大小,当图像小于其原始大小时,我想设置img 宽度到 100%,但是当 image-container 大于图像的原始宽度时,我希望将图像定位在容器内部的中心。

有什么想法吗?

.server-listing {
    width: 100%;
    height: auto;
    margin-bottom: 10px;
}

.server-listing .image {
    text-align: center;
}

.server-listing .image img {
    width: 100%;
    height: auto;
}

我目前的 CSS,真的很基础,我需要指导 - 谢谢大家!

<?php foreach($this->model->data['servers'] as $server) { ?>
    <div class="server-listing">
        <div class="image">
            <img src="x.jpeg">
        </div>
    </div>
<?php } ?>

我的 phtml 页面

(注意:图片可以是任意大小)

【问题讨论】:

  • 请尝试 max-width:100%;而不是宽度
  • 成功了@YogeshSharma,非常感谢!
  • 是的@YogeshSharma,再次感谢。
  • @YogeshSharma 请把它写成答案!你打败了我,所以如果你添加你自己的:-),我会收回我的答案(只需在评论中标记我,这样我就知道回来这样做!)
  • 很高兴你能成功。 :) @Jackhardcastle

标签: css image layout


【解决方案1】:

max-width 是您应该使用的 CSS 属性!

.server-listing {
    width: 100%;
    height: auto;
    margin-bottom: 10px;
    background-color: lime;
}
.server-listing .image {
    text-align: center;
}
.server-listing .image img {
    max-width: 100%;
    height: auto;
}
<div class="server-listing">
    <div class="image">
        <img src="http://placehold.it/500" />
    </div>
</div>

你可能必须进入全屏模式才能真正玩这个!

【讨论】:

  • 评论区有人打败了你——不过,非常感谢。
  • @Jackhardcastle 要求评论者提出一个答案来代替我的!
  • 你做得很好@gvee。在短时间内创建演示 :) 为您的快速工作点赞
【解决方案2】:

请尝试 max-width:100%;而不是宽度。

max-width 属性用于设置元素的最大宽度。

这可以防止 width 属性的值变得大于 max-width。

【讨论】:

  • 老兄,您需要将其扩展为完整的答案。目前只是一条评论!
  • @gvee 我希望现在更好:)
【解决方案3】:

看看它对小图像和大图像的工作原理:

.server-listing {
    display: inline-block;
    max-width: 100vw;
    height: auto;
}

.server-listing .image {
    text-align: center;  
    margin-bottom: 10px;  
    background-color: gray;  
}

.server-listing .image img {
    max-width: 95vw;
    height: auto;
}
<div class='server-listing'>
  <div class='image'>
    <img src='https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/c0.0.50.50/p50x50/10342461_799073063461766_6339462327156793350_n.jpg?oh=169a0d52644a444c2f723b1d1ec6c64b&oe=558BEB09&__gda__=1435700277_205a1d24a106c52496fe0e3eb20470e6' />
  </div>
<div>
<div class='server-listing'>
  <div class='image'>
    <img src='http://www.zastavki.com/pictures/1680x1050/2010/Animals_Cats_Cat_023761_.jpg' />
   </div>
</div>

【讨论】:

    【解决方案4】:

    我认为你必须添加边距和显示:

    .server-listing .image img
        {
            width: 100%;
            height: auto;
            margin: 0px auto;
            display: block;
        }
    

    【讨论】:

    • 不 - 其他人在 cmets 中得到了它,width: 100% 将 img 宽度设置为父容器的 100% - 但是 max-width 会将 img 宽度设置为它的最大宽度 100 %。不过谢谢!
    • 对,它是最大宽度(使用骨架,我已经忘记了:))。
    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2016-06-11
    • 2013-02-06
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2017-02-24
    相关资源
    最近更新 更多