当前位置:首页 > JavaScript

js 实现 图片居中

2026-03-16 05:58:14JavaScript

使用 CSS Flexbox 实现图片居中

将图片容器设置为 Flex 布局,通过 justify-contentalign-items 属性实现水平和垂直居中。

<div class="container">
  <img src="image.jpg" alt="Centered Image">
</div>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* 可根据需要调整高度 */
}

使用 CSS Grid 实现图片居中

通过 Grid 布局的 place-items 属性快速实现居中效果。

js 实现 图片居中

.container {
  display: grid;
  place-items: center;
  height: 100vh;
}

使用绝对定位实现图片居中

结合绝对定位和 transform 属性实现精确居中。

.container {
  position: relative;
  height: 100vh;
}

.container img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

使用 text-align 实现水平居中

适用于行内元素或 inline-block 元素的水平居中。

js 实现 图片居中

<div class="container">
  <img src="image.jpg" alt="Centered Image">
</div>
.container {
  text-align: center;
}

使用 margin 自动实现居中

适用于已知尺寸的块级元素居中。

img {
  display: block;
  margin: 0 auto;
  width: 300px; /* 需要指定宽度 */
}

使用 JavaScript 动态计算居中位置

通过 JavaScript 计算并设置图片位置实现动态居中。

<img id="centered-image" src="image.jpg" alt="Centered Image">
function centerImage() {
  const img = document.getElementById('centered-image');
  const windowHeight = window.innerHeight;
  const windowWidth = window.innerWidth;
  const imgHeight = img.clientHeight;
  const imgWidth = img.clientWidth;

  img.style.position = 'absolute';
  img.style.top = `${(windowHeight - imgHeight) / 2}px`;
  img.style.left = `${(windowWidth - imgWidth) / 2}px`;
}

window.addEventListener('load', centerImage);
window.addEventListener('resize', centerImage);

标签: 图片js
分享给朋友:

相关文章

vue实现拖动图片验证

vue实现拖动图片验证

实现拖动图片验证的思路 拖动图片验证是一种常见的验证码形式,用户需要将图片拖动到指定位置完成验证。在Vue中实现这一功能需要结合HTML5的拖放API和Vue的数据绑定特性。 核心实现步骤 HTML…

vue实现图片拖拽

vue实现图片拖拽

实现图片拖拽功能 在Vue中实现图片拖拽功能可以通过HTML5的拖放API结合Vue的事件处理来完成。以下是一个完整的实现方法: 基础拖拽实现 为图片元素添加draggable属性并绑定相关事件:…

vue实现图片查看

vue实现图片查看

Vue 实现图片查看功能 在 Vue 中实现图片查看功能,可以通过原生实现或使用第三方库。以下是几种常见的方法: 原生实现方式 使用 Vue 的指令和事件绑定实现基础的图片查看功能。 <te…

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

jquery js

jquery js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够更高…

vue实现图片查看

vue实现图片查看

实现图片查看功能 在Vue中实现图片查看功能可以通过多种方式完成,常见的有使用原生HTML5的<dialog>元素、第三方组件库(如Element UI、Vant等)或专用插件(如view…