0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【フロントエンド1000本ノック】0038_object-fitプロパティ(contain, cover)を使い、コンテナのサイズが変動しても画像の縦横比を維持する実装を行え。

Posted at

object-fit プロパティ

 <img> タグに widthheight を指定すると、画像の縦横比が崩れて、引き伸ばされたり潰れたりすることがあります。object-fit は、その問題を解決するためのプロパティです。

背景画像における background-size プロパティと似た動きを、<img> 要素に対して行います。

containcover

contain
画像の全体見えるように、縦横比を保ったままコンテナに収まるように縮小されます。コンテナと画像の縦横比が違う場合、余白ができます。

cover
コンテナを完全に覆うように、縦横比を保ったまま拡大・縮小されます。画像の一部が切り取られる可能性があります。

作成したコード

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>フロントエンド1000本ノック 0038</title>
    <style>
      div {
        margin-bottom: 100px;
      }
    </style>
</head>
<body>
    <main>
      <h1>object-fit プロパティ</h1>

      <div style="width: 400px; height: 200px;">
        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='300'%3E%3Crect width='300' height='300' fill='%234CAF50'/%3E%3Ccircle cx='150' cy='150' r='100' fill='%23FFC107'/%3E%3Ctext x='150' y='165' font-size='48' text-anchor='middle' fill='white' font-family='Arial'%3E300x300%3C/text%3E%3C/svg%3E" alt="正方形の画像(300x300px)" style="width: 100%; height: 100%; object-fit: contain;">
      </div>

      <div style="width: 400px; height: 200px;">
        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='300'%3E%3Crect width='300' height='300' fill='%234CAF50'/%3E%3Ccircle cx='150' cy='150' r='100' fill='%23FFC107'/%3E%3Ctext x='150' y='165' font-size='48' text-anchor='middle' fill='white' font-family='Arial'%3E300x300%3C/text%3E%3C/svg%3E" alt="正方形の画像(300x300px)" style="width: 100%; height: 100%; object-fit: cover;">
      </div>

    </main>
    <footer>
      <p>Copyright 2025</p>
      <p>フロントエンド1000本ノック</p>
    </footer>

</body>
</html>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?