CSS图片居中显示不变形,只显示中间部分
warning:
这篇文章距离上次修改已过204天,其中的内容可能已经有所变动。
要在CSS中使图片居中显示,并且只显示图片的中间部分,可以使用background-position
和background-size
属性。以下是一个示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Crop Example</title>
<style>
.crop-image {
width: 200px; /* 设置显示框的宽度 */
height: 200px; /* 设置显示框的高度 */
background-image: url('path_to_image.jpg'); /* 设置背景图片 */
background-position: center; /* 背景图片居中 */
background-size: cover; /* 背景图片覆盖整个元素区域 */
background-repeat: no-repeat; /* 背景图片不重复 */
position: relative; /* 相对定位 */
}
/* 使用伪元素进行中间裁剪 */
.crop-image::before {
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto; /* 保证绝对定位的元素居中 */
width: 50%; /* 设置宽度为父元素的一半 */
height: 50%; /* 设置高度为父元素的一半 */
background-image: inherit; /* 继承父元素的背景图片 */
background-position: center; /* 背景图片居中 */
background-size: contain; /* 背景图片包含整个元素区域 */
border-radius: 50%; /* 边框半径,形成圆形 */
}
</style>
</head>
<body>
<div class="crop-image"></div>
</body>
</html>
在这个例子中,.crop-image
类定义了一个显示框,并设置了背景图片。使用:before
伪元素,我们创建了一个圆形遮罩,它的大小是其父元素的一半,并且通过background-size: contain
确保只显示图片的中间部分。这样,图片就会以圆形方式居中显示,并且只显示图片的中间部分。
请将path_to_image.jpg
替换为你想要显示的图片路径。
评论已关闭