当前位置:首页 > 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 实现图片轮播的方法 使用第三方库(推荐) 安装 vue-awesome-swiper 库,这是基于 Swiper 的 Vue 封装: npm install swiper vue-a…

vue实现图片打点

vue实现图片打点

实现图片打点的基本思路 图片打点功能通常指在图片上添加可交互的标记点,点击或悬停时显示相关信息。Vue实现该功能需要结合DOM操作和事件监听。 核心步骤 准备图片和容器 在Vue组件中设置一个相对定…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

vue实现图片预览

vue实现图片预览

实现图片预览功能 在Vue中实现图片预览功能可以通过多种方式完成,常见的有使用原生HTML5的<dialog>元素、第三方库如viewer.js或vue-photo-preview,以及自…