You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Next.js中调整next/image组件大小,适配Bootstrap卡片显示需求

原因

你自定义样式未生效主要有两个原因:

  1. Next.js 内置的Image组件默认会读取本地图片的原始宽高,并添加强制宽高样式,优先级高于你外层容器的自定义样式
  2. Bootstrap Card 组件默认会给内部图片设置width: 100%的规则,让图片撑满整个卡片头部

实现方案

你可以通过以下方式修改代码,实现图片缩放到原尺寸60%且不撑满卡片的效果:

1. 修改JSX代码

import Image from 'next/image'
import logo from '../public/delta-logo.png'
import { Card, Button } from 'react-bootstrap'
import styles from './landing.module.css'

import 'bootstrap/dist/css/bootstrap.min.css'

export default function LandingPage() {
  return (
    <Card style={{ width: '18rem' }}>
      {/* 外层容器负责居中 */}
      <div className={styles.logoWrapper}>
        <Image 
          src={logo} 
          alt='Picture of our Logo'
          // 关闭Next.js默认的尺寸限制
          width={0}
          height={0}
          sizes="100vw"
          className={styles.resizedLogo}
        />
      </div>

      <Card.Body className='text-center'>
        <Card.Title>Card Title</Card.Title>
        <Card.Text>
          Some quick example text to build on the card title and make up the
          bulk of the card's content.
        </Card.Text>
        <Button variant='primary'>Go somewhere</Button>
      </Card.Body>
    </Card>
  )
}

2. 在landing.module.css中添加对应样式

.logoWrapper {
  width: 100%;
  padding: 12px 0;
  display: flex;
  justify-content: center;
}
.resizedLogo {
  /* 按原尺寸缩放60%,也可以换成 width: 60% 按容器宽度比例缩放 */
  transform: scale(0.6);
  height: auto;
}

简化方案(不需要额外CSS文件)

如果你不想新增CSS样式,也可以直接在Image组件上通过style属性内嵌样式:

<Image 
  src={logo} 
  alt='Picture of our Logo'
  width={0}
  height={0}
  sizes="100vw"
  style={{
    width: '60%',
    height: 'auto',
    margin: '12px auto',
    display: 'block'
  }}
/>

注意事项

如果你使用的是Next.js 12及更早版本,把width={0} height={0} sizes="100vw"替换为layout="intrinsic"即可生效。

内容的提问来源于stack exchange,提问作者rf guy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:27:03