任意の画像が与えられた場合、その画像の中心から正方形を切り取り、指定された正方形内に表示したいと考えています。
この質問は次のようなものです:CSS サイズ変更およびトリミングされた画像を表示するただし、画像のサイズがわからないため、設定された余白は使用できません。
ベストアンサー1
解決策の 1 つは、切り取られた寸法に合わせてサイズ設定された要素内の中央に配置された背景画像を使用することです。
基本的な例
.center-cropped {
width: 100px;
height: 100px;
background-position: center center;
background-repeat: no-repeat;
}
<div class="center-cropped"
style="background-image: url('https://via.placeholder.com/200');">
</div>
img
タグ付きの例
このバージョンではimg
タグが保持されるため、ドラッグや右クリックで画像を保存することができます。パーカー・ベネット不透明度のトリック用。
.center-cropped {
width: 100px;
height: 100px;
background-position: center center;
background-repeat: no-repeat;
overflow: hidden;
}
/* Set the image to fill its parent and make transparent */
.center-cropped img {
min-height: 100%;
min-width: 100%;
/* IE 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
/* IE 5-7 */
filter: alpha(opacity=0);
/* modern browsers */
opacity: 0;
}
<div class="center-cropped"
style="background-image: url('https://via.placeholder.com/200');">
<img src="https://via.placeholder.com/200" />
</div>
object-fit
/-position
のCSS3 画像仕様object-fit
とプロパティを定義しobject-position
、これらを組み合わせることで、要素の画像コンテンツのスケールと位置をより細かく制御できますimg
。これらを使用すると、目的の効果を実現できます。
.center-cropped {
object-fit: none; /* Do not scale the image */
object-position: center; /* Center the image within the element */
height: 100px;
width: 100px;
}
<img class="center-cropped" src="https://via.placeholder.com/200" />