【问题标题】:React App - Div is centered on local host but not when deployed to github pagesReact App - Div 以本地主机为中心,但不是在部署到 github 页面时
【发布时间】:2021-04-04 10:15:54
【问题描述】:

我的 create-react-app 部署在 github 页面上时遇到问题。

在第一张图片中,它是我在 github 页面上部署的应用程序。图片应该位于页面中间。

第二张图片显示了在我的本地主机上使用 npm start 运行时的样子。

这是代码,如果有人可以帮助我弄清楚如何使图像在部署中居中,那将是非常感谢:

在我的 About.js 中:

import React from 'react';
import me from '../../photos/portraits/portraits8.jpg';
import './About.css';


const About = () =>  {
  return(
    <div>
    <figure className="figure center">
      <img src={me} alt="" className="about-img"/>
      <figcaption className="figcaption bg-color">Hi, my name is Thomas Nguyen, and I’m a freelance photographer based in Morgan Hill, CA. My main focus is automotive photography as well as portrait photography. I'm also a Software Engineer, and this whole website was built with React, Javascript, CSS, and HTML!</figcaption>
    </figure>
    </div>
  );
}


export default About;


在我的 About.css 中:

.about-img{
  /*max-height: 500px;*/
  max-height: 400px;
  height: auto\9;
  width: auto;
}

.center {
  display: block;
  margin-left: auto;
  margin-right: auto;
}


.figure {
  display: table;
  margin: 0;
}

.figcaption {
  display: table-caption;
  caption-side: bottom;
  padding: 10px;
}

.bg-color{
  background-color: rgba(78, 100, 124, .1);

}

【问题讨论】:

    标签: html css reactjs github github-pages


    【解决方案1】:

    唯一的谜团是它首先是如何在本地环境中工作的。一旦我将代码复制到一个全新的 HTML 文件中,它就不起作用了。 .center 类中编写的所有样式都没有被浏览器应用,因此没有内容居中。原因是您不能在display: table 元素上应用边距。如果您检查您的类,您会看到 .figure 类覆盖了 .center 类的 display: block 属性。

    因此,这样做:

    <style>
    .center {
      display: flex;
      justify-content: center;
    }
    </style>
    
    <div className="center">
        <figure className="figure">
          ...rest of the code
        </figure>
    </div>
    

    因此,从图形标记中删除 .center 类,并将其放在包装 div 上。然后更改 .center 类的 CSS 属性,使其正确居中。

    【讨论】:

    • 嗯,这真的很奇怪。不知道为什么它在我的本地主机中工作。谢谢!这非常有效。
    猜你喜欢
    • 2022-10-05
    • 1970-01-01
    • 2019-04-08
    • 2021-05-17
    • 2022-11-19
    • 2020-11-26
    • 1970-01-01
    • 2023-02-09
    • 2015-04-08
    相关资源
    最近更新 更多