「div」コンテナに合うように画像を自動化するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/3029422

  •  26-09-2019
  •  | 
  •  

質問

幅:高さ比を維持しながら、より小さな幅Divコンテナに収まるように、大きな画像をどのように自動化しますか?


例:stackoverflow.com-画像がエディターパネルに挿入され、画像が大きすぎてページに収まるには大きすぎると、画像は自動的にサイズ変更されます。

役に立ちましたか?

解決

明示的な幅または高さを画像タグに適用しないでください。代わりに、それを与えてください:

max-width:100%;
max-height:100%;

また、 height: auto; 幅を指定する場合のみ。

例: http://jsfiddle.net/xwrvxser/1/

img {
    max-width: 100%;
    max-height: 100%;
}

.portrait {
    height: 80px;
    width: 30px;
}

.landscape {
    height: 30px;
    width: 80px;
}

.square {
    height: 75px;
    width: 75px;
}
Portrait Div
<div class="portrait">
    <img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>

Landscape Div
<div class="landscape">
    <img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>

Square Div
<div class="square">
    <img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>

他のヒント

オブジェクトフィット

これを行う別の方法があることがわかりました。

<img style='height: 100%; width: 100%; object-fit: contain'/>

仕事をします。 CSS 3のものです。

フィドル: http://jsfiddle.net/mbhb4/7364/

現在、JPEGやPNGファイルなどの固定サイズの画像を使用して、決定論的な方法でこれを正しく行う方法はありません。

画像を比例してサイズ変更するには、設定する必要があります また 高さまたは幅は「100%」ですが、両方ではありません。 両方を「100%」に設定すると、画像が伸びます。

高さと幅を実行するかどうかを選択することは、画像とコンテナの寸法によって異なります。

  1. あなたの画像と容器が「ポートレート形状」または両方の「景観形状」(それぞれ幅よりも高い、または背が高いよりも高い)の両方である場合、高さまたは幅のどちらが「%100」であるかは関係ありません。
  2. あなたの画像が肖像画であり、あなたのコンテナが風景である場合、あなたは設定する必要があります height="100%" 画像。
  3. あなたの画像が風景であり、あなたのコンテナが肖像画である場合、あなたは設定する必要があります width="100%" 画像。

画像が可変サイズのベクトル画像形式であるSVGである場合、コンテナに適合する拡張が自動的に発生する可能性があります。

SVGファイルに、これらのプロパティが設定されていないことを確認する必要があります。 <svg> 鬼ごっこ:

height
width
viewbox

ほとんどのベクトル描画プログラムは、SVGファイルをエクスポートするときにこれらのプロパティを設定するため、エクスポートするたびにファイルを手動で編集するか、スクリプトを作成する必要があります。

これは、供給された画像が小さすぎてDIVに収まるには小さすぎるか大きすぎる場合でも、ストレッチせずにDIV内でIMGを垂直に、および水平に整列させるソリューションです。

HTMLコンテンツ:

<div id="myDiv">
  <img alt="Client Logo" title="Client Logo" src="Imagelocation" />
</div>

CSSコンテンツ:

#myDiv
{
  height: 104px;
  width: 140px;
}
#myDiv img
{
  max-width: 100%;
  max-height: 100%;
  margin: auto;
  display: block;
}

jqueryパート:

var logoHeight = $('#myDiv img').height();
    if (logoHeight < 104) {
        var margintop = (104 - logoHeight) / 2;
        $('#myDiv img').css('margin-top', margintop);
    }

それを簡単に!

容器を与えます 修繕 height そして、のために img 内部にタグを付け、設定します widthmax-height.

<div style="height: 250px">
     <img src="..." alt=" " style="width: 100%;max-height: 100%" />
</div>

違いは、あなたが設定することです width ではなく100%になること max-width.

美しいハック。

画像が応答する2つの方法があります。

  1. 画像が背景画像の場合。
#container{
    width: 300px;
    height: 300px;
    background-image: url(http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
}

<div id="container"><div>

それを実行します ここ


ただし、使用する必要があります img 画像を配置するタグが優れています background-image の面では SEO 書くことができるように キーワード の中に altimg 鬼ごっこ。それで、ここであなたは画像を応答することができます。

  1. 画像が入っているとき img 鬼ごっこ。
#container{
    max-width: 400px;
    overflow: hidden;
}
img{
    width: 100%;
    object-fit: contain;
}

<div id="container">
   <img src="http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg" alt="your_keyword"/>
<div>

それを実行します ここ

私の解決策をチェックしてください: http://codepen.io/petethepig/pen/dvfsa

JavaScriptコードなしで、純粋なCSSで書かれています。あらゆるサイズとあらゆる方向の画像を処理できます。

そのようなHTMLを考えると:

<div class="image">
  <div class="trick"></div>
  <img src="http://placekitten.com/415/200"/>
</div>

CSSコードは次のとおりです。

.image {
  font-size: 0;
  text-align: center;
  width: 200px;  /* Container's dimensions */
  height: 150px;
}
img {
  display: inline-block;
  vertical-align: middle;
  max-height: 100%;
  max-width: 100%;
}
.trick {
  display: inline-block;
  vertical-align: middle;
  height: 150px;
}

画像を背景としてdivに設定してから、 CSSバックグラウンドサイズのプロパティ:

background-size: cover;

そうなる 「背景画像を可能な限り大きくするために、背景領域が背景画像で完全に覆われているようにスケーリングします。背景画像の一部は、背景の位置領域内で見られない場合があります」 -- w3schools

私は、多くのオプションで必要なものを正確に行うjQueryプラグインを公開しました。

https://github.com/gestixi/image-scale

使用法:

HTML

<div class="image-container">
    <img class="scale" data-scale="best-fit-down" data-align="center" src="img/example.jpg">
</div>

JavaScript

$(function() {
    $("img.scale").imageScale();
});

このソリューションは画像を伸ばしず、容器全体を埋めますが、画像の一部をカットします。

HTML:

 <div><img src="/images/image.png"></div>

CSS:

div {
    width: 100%;
    height: 10em;
    overflow: hidden;

img {
    min-width: 100%;
    min-height: 100%;
}

以下は私にとって完璧に機能します:

img{
   height: 99999px;
   object-fit:contain;
   max-height: 100%;
   max-width: 100%;    
   display: block;
   margin: auto auto;
}

JavaScriptを必要とせずに、はるかに優れた解決策があります。それは完全に反応が良く、私はそれをたくさん使っています。多くの場合、任意のアスペクト比の画像を指定されたアスペクト比を持つコンテナ要素に適合させる必要があります。そして、このこと全体を完全に反応させることは必須です。

/* For this demo only */
.container {
  max-width: 300px;
  margin: 0 auto;
}
.img-frame {
  box-shadow: 3px 3px 6px rgba(0, 0, 0, .15);
  background: #ee0;
  margin: 20px auto;
}

/* This is for responsive container with specified aspect ratio */
.aspect-ratio {
  position: relative;
}
.aspect-ratio-1-1 {
  padding-bottom: 100%;
}
.aspect-ratio-4-3 {
  padding-bottom: 75%;
}
.aspect-ratio-16-9 {
  padding-bottom: 56.25%;
}

/* This is the key part - position and fit the image to the container */
.fit-img {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  max-width: 80%;
  max-height: 90%
}
.fit-img-bottom {
  top: auto;
}
.fit-img-tight {
  max-width: 100%;
  max-height: 100%
}
<div class="container">

  <div class="aspect-ratio aspect-ratio-1-1 img-frame">
    <img src="//placehold.it/400x300" class="fit-img" alt="sample">
  </div>

  <div class="aspect-ratio aspect-ratio-4-3 img-frame">
    <img src="//placehold.it/400x300" class="fit-img fit-img-tight" alt="sample">
  </div>

  <div class="aspect-ratio aspect-ratio-16-9 img-frame">
    <img src="//placehold.it/400x400" class="fit-img" alt="sample">
  </div>

  
  <div class="aspect-ratio aspect-ratio-16-9 img-frame">
    <img src="//placehold.it/300x400" class="fit-img fit-img-bottom" alt="sample">
  </div>
  
</div>

最大幅と最大高さを個別に設定できます。画像は最小のものを尊重します(画像の値とアスペクト比に応じて)。また、必要に応じて画像を設定することもできます(たとえば、無限の白い背景の製品写真の場合、それを底に簡単に配置できます)。

あなたの画像に必要な高さと幅を、u003Cimg>鬼ごっこ。適切なスタイルのタグで高さ/幅を与えることを忘れないでください。

の中にu003Cimg>タグ、与える max-heightmax-width 100%として。

<div style="height:750px; width:700px;">
    <img alt="That Image" style="max-height:100%; max-width:100%;" src="">
</div>

適切なクラスを正しく取得した後、詳細を追加できます。

以下のコードは以前の回答から採用されており、呼ばれる画像を使用して私によってテストされています storm.jpg.

これは、画像を表示する簡単なページの完全なHTMLコードです。これは完璧に機能し、www.resizemybrowser.comで私によってテストされました。 CSSコードをHTMLコードの上部に置きます。写真コードをどこにでも置いてください。

<html>
    <head>
        <style type="text/css">
            #myDiv
            {
                  height: auto;
                  width: auto;
            }
            #myDiv img
            {
                max-width: 100%;
                max-height: 100%;
                margin: auto;
                display: block;
            }
        </style>
    </head>

    <body>
        <div id="myDiv">
            <img src="images/storm.jpg">
        </div>
    </body>
</html>

ブラウザに配置する場所の高さを伝える必要があります。

.example {
    height: 220px; /* DEFINE HEIGHT */
    background: url('../img/example.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
}

この方法で、水平方向と垂直の両方でハイパーリンク内の画像を比例して中心にして拡大しました。

#link {
    border: 1px solid blue;
    display: table-cell;
    height: 100px;
    vertical-align: middle;
    width: 100px;
}
#link img {
    border: 1px solid red;
    display: block;
    margin-left: auto;
    margin-right: auto;
    max-height: 60px;
    max-width: 60px;
}

Internet Explorer、Firefox、およびSafariでテストされました。

センターリングの詳細はです ここ.

Thorn007からの受け入れられた答え いつ機能しません 画像が小さすぎます.

これを解決するために、aを追加しました スケールファクター. 。このようにして、画像を大きくし、Divコンテナを埋めます。

例:

<div style="width:400px; height:200px;">
  <img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" />
</div>

ノート:

  1. WebKitについては、追加する必要があります -webkit-transform:scale(4); -webkit-transform-origin:left top; スタイルで。
  2. 4のスケール係数で、最大幅= 400/4 = 100と最大高さ= 200/4 = 50があります
  3. 別の解決策は、最大幅と最大高さを25%に設定することです。さらに簡単です。
<style type="text/css">
    #container{
        text-align: center;
        width: 100%;
        height: 200px; /* Set height */
        margin: 0px;
        padding: 0px;
        background-image: url('../assets/images/img.jpg');
        background-size: content; /* Scaling down large image to a div */
        background-repeat: no-repeat;
        background-position: center;
    }
</style>

<div id="container>
    <!-- Inside container -->
</div>

編集: 以前のテーブルベースの画像ポジショニングには、インターネットエクスプローラー11に問題がありました(max-height うまくいきません display:table 要素)。 Internet Explorer 7とInternet Explorer 11の両方で正常に機能するだけでなく、コードも少ないコードで正常に機能するだけでなく、インラインベースのポジショニングに置き換えました。


これが私のテーマについての私の見解です。コンテナに指定されたサイズがある場合にのみ機能します(max-widthmax-height コンクリートサイズのないコンテナと仲良くしないようには見えません)が、CSSコンテンツを再利用できるように書いた(追加する picture-frame クラスと px125 既存のコンテナへのサイズクラス)。

CSSで:

.picture-frame
{
    vertical-align: top;
    display: inline-block;
    text-align: center;
}

.picture-frame.px125
{
    width: 125px;
    height: 125px;
    line-height: 125px;
}

.picture-frame img
{
    margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */
    max-width: 100%;
    max-height: 100%;
    display: inline-block;
    vertical-align: middle;
    border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */
}

そしてHTMLで:

<a href="#" class="picture-frame px125">
    <img src="http://i.imgur.com/lesa2wS.png"/>
</a>

デモ

/* Main style */

.picture-frame
{
    vertical-align: top;
    display: inline-block;
    text-align: center;
}

.picture-frame.px32
{
    width: 32px;
    height: 32px;
    line-height: 32px;
}

.picture-frame.px125
{
    width: 125px;
    height: 125px;
    line-height: 125px;
}

.picture-frame img
{
    margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */
    max-width: 100%;
    max-height: 100%;
    display: inline-block;
    vertical-align: middle;
    border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */
}

/* Extras */

.picture-frame
{
    padding: 5px;
}

.frame
{
    border:1px solid black;
}
<p>32px</p>
<a href="#" class="picture-frame px32 frame">
    <img src="http://i.imgur.com/lesa2wS.png"/>
</a>
<a href="#" class="picture-frame px32 frame">
    <img src="http://i.imgur.com/kFMJxdZ.png"/>
</a>
<a href="#" class="picture-frame px32 frame">
    <img src="http://i.imgur.com/BDabZj0.png"/>
</a>
<p>125px</p>
<a href="#" class="picture-frame px125 frame">
    <img src="http://i.imgur.com/lesa2wS.png"/>
</a>
<a href="#" class="picture-frame px125 frame">
    <img src="http://i.imgur.com/kFMJxdZ.png"/>
</a>
<a href="#" class="picture-frame px125 frame">
    <img src="http://i.imgur.com/BDabZj0.png"/>
</a>


編集:JavaScript(Upscaling Images)を使用してさらに改善する可能性:

function fixImage(img)
{
    var $this = $(img);
    var parent = $this.closest('.picture-frame');
    if ($this.width() == parent.width() || $this.height() == parent.height())
        return;

    if ($this.width() > $this.height())
        $this.css('width', parent.width() + 'px');
    else
        $this.css('height', parent.height() + 'px');
}

$('.picture-frame img:visible').each(function
{
    if (this.complete)
        fixImage(this);
    else
        this.onload = function(){ fixImage(this) };
});

として ここで答えました, 、使用することもできます vh の代わりにユニット max-height: 100% ブラウザで動作しない場合(Chromeのような):

img {
    max-height: 75vh;
}

多くの人が提案していると思います オブジェクトフィット これは良い選択肢です。しかし、あなたが望むなら働くことです 古いブラウザも同様です, 、簡単にそれを行う別の方法があります。

ここで私の答えをチェックアウトしてください:IEとオブジェクトフィットのエッジ修正:カバー。

その非常に簡単です。私が取ったアプローチは、コンテナ内に画像を配置することでした 絶対の その後 中央に置きます 組み合わせの使用:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

それが中央にあると、私は画像に与えます、

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

これにより、画像がオブジェクトフィットの効果を取得します:カバー。


上記のロジックのデモンストレーションです。

https://jsfiddle.net/furqan_694/s3xle1gp/

このロジックは、すべてのブラウザで機能します。

私にとっては機能しているように見える簡単なソリューション(4段階の修正!!)は以下です。この例では、幅を使用して全体のサイズを決定しますが、代わりに高さを使用するためにフリップすることもできます。

  1. 画像コンテナにCSSスタイリングを適用します(たとえば、u003Cimg> ))
  2. 幅プロパティを必要な寸法に設定します
    • 寸法の場合は、使用します % 相対サイズ、または自動化する(画像コンテナまたはディスプレイに基づく)
    • 使用する px (またはその他)静的、または寸法を設定する
  3. 幅に基づいて、高さプロパティを自動的に調整するように設定します
  4. 楽しい!

例えば、

<img style="width:100%; height:auto;"
    src="https://googledrive.com/host/0BwDx0R31u6sYY1hPWnZrencxb1k/thanksgiving.png"
/>

受け入れられたものを含むすべての提供された回答は、仕事 それだけ という仮定の下で div ラッパーは固定サイズです。これがそれを行う方法です なんでもいい のサイズ div ラッパーはそうであり、これはレスポンシブページを開発する場合に非常に便利です。

これらの宣言をあなたの中に書いてください DIV セレクタ:

width: 8.33% /* Or whatever percentage you want your div to take */
max-height: anyValueYouWant /* (In px or %) */

次に、これらの宣言をあなたの中に入れます IMG セレクタ:

width: "100%" /* Obligatory */
max-height: anyValueYouWant /* (In px or %) */

非常に重要:

の値 maxHeight でなければなりません 同じ 両方のために DIVIMG セレクター。

次のコードを使用してこの問題を修正しました。

<div class="container"><img src="image_url" /></div>
.container {
    height: 75px;
    width: 75px;
}

.container img {
    object-fit: cover;
    object-position: top;
    display: block;
    height: 100%;
    width: 100%;
}

簡単な解決策は、FlexBoxを使用することです。コンテナのCSSを次のように定義します。

.container{
    display: flex;
    justify-content: center;
    align-items: center;
    align-content: center;
    overflow: hidden;
    /* Any custom height */
}

含まれる画像幅を100%に調整すると、寸法が保存されているコンテナに素敵な中心的な画像が表示されます。

ブートストラップを使用している場合は、 img-responsive クラスへ img 鬼ごっこ:

<img class="img-responsive" src="img_chania.jpg" alt="Chania">

ブートストラップ画像

解決策は少し数学で簡単です...

画像をDIVに入れてから、イメージを指定するHTMLファイルに配置します。画像のピクセル値を使用して、幅と高さの値をパーセンテージで設定して、幅の正確な比率を高さと計算します。

たとえば、幅200ピクセルと高さ160ピクセルの画像があるとします。幅が100%になると安全に言うことができます。これは、値が大きいためです。次に、高さの値を計算するには、高さを幅で分割するだけで、パーセンテージ値は80%です。コードでは、このようなものになります...

<div class="image_holder_div">
    <img src="some_pic.png" width="100%" height="80%">
</div>

私の答えを確認してください、 イメージを応答します - 最も簡単な方法 -

img{
    width: 100%;
    max-width: 800px;
}

これを行う最も簡単な方法は、使用することです object-fit:

<div class="container">
  <img src="path/to/image.jpg">
</div>

.container{
   height: 300px;
}

.container img{
  height: 100%;
  width: 100%;
  object-fit: cover;
}

Bootstrapを使用している場合は、追加してください img-responsive クラスと変更

.container img{
    object-fit: cover;
}

または、単に使用することもできます。

background-position:center;
background-size:cover;

これで、画像はdivのすべてのスペースを取ります。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top