如何在ReactJS中使用CSS居中图片

9

我正在使用ReactJS create-react-app来构建网站。我想在我的主页上使用css将图片水平居中,但它仍然保持左对齐。

我已经通过类声明将.jpg文件导入到.js文件中,并显示在页面上,但它没有遵循我在index.css文件中进行的类修改。

//在Cur.js文件中

import React from 'react';
import Image from 'react-image-resizer';
import cur from './cur.jpg';

function Cur() {

    return (
      <div>
        <Image
          img src={cur} alt="cur" class="center"
          height={350}
          width={700}
        />
      </div>
    );

}

export default Cur;

//在 index.css 文件中

.center{
    text-align: center;
    display: block;
    justify-content: center;
    align-items: center;
    margin: auto;
    width: 100%;
  }
8个回答

6
<Image
    img src={cur} alt="cur"
    height={350}
    width={700}
    style={{ alignSelf: 'center' }}
/>

您可以将内联样式分离,或者使用styled-components代替。

当我在Cur.js文件中实现这个时,它仍然保持左对齐。 - opposite-people
你应该在父元素中添加 flex - nrion

4

为 div 设置一个类名,例如 className="container-div",并在 CSS 样式表中进行样式设置。

.container-div{ 
display: flex;
height: 100vh;
width: 100vw; 
align-items: center;
justify-content: center;
}

使用height和width属性可以确保您的容器覆盖整个屏幕。


我必须更改/纠正底部属性的拼写。居中 - C-Note187
我明白了,谢谢。 - Georg

3

HTML:

 <div className="image-container">
    <img src={logo} alt="logo"/>
 </div>

CSS文件:

.image-container {
   display: flex;
   justify-content: center;
   align-items: center;
}

图片来自于 'react-image-resizer' 库。 - Swaraj Gandhi
1
这对我有用。谢谢@Junie。 - Radu Bartan

3

试试这个...属性称为className而不是class。

import React from 'react';
import Image from 'react-image-resizer';
import from "index.css"
import cur from './cur.jpg';

function Cur() {

    return (
      <div>
        <Image
          img src={cur} alt="cur" class="center"
          height={350}
          width={700}
        />
      </div>
    );

}

export default Cur;

即使进行了这种改变,它仍然左对齐,我的.css实现有什么问题吗? - opposite-people
此外,这并不是导致问题的原因,但属性应该只是 src={} 而不是 img src="" - Fernando Salas

2

React使用className代替class

更改为:

img src={cur} alt="cur" class="center"

to

img src={cur} alt="cur" className="center"

1
在父级 div 的 CSS 中添加:

.parent {
    display: flex;
    justify-content: center;
}

这将居中你的图片。


1
我的问题是在CSS样式中缺少了"display: flex"。将其添加到其他样式中,解决了我的问题。

0
import React from 'react';
import Image from 'react-image-resizer';
import cur from './cur.jpg';

function Cur() {

    return (
      <div>
        <Image src={cur} alt="cur" className="center"/>
      </div>
    );

}

export default Cur;



body,html{
   height:100%,
   min-height:100%
}

.center{
text-align:center;//for texts
height:100%;
display:flex; 
align-items:center;
justify-content:center;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接