简体   繁体   English

React JS 组件未应用 CSS 边距

[英]React JS component not applying CSS margin

With react I have created a very simple card component in a Card.jsx file.通过 react,我在Card.jsx文件中创建了一个非常简单的卡片组件。 The component looks like this.该组件看起来像这样。

class Card extends React.Component{

  render() {
    return (
      <div className={style.mainContainer}>
        <div className={style.container}>
          <div className={style.title}>Hello world</div>
          <div className={style.value}></div>
        </div>
      </div>
    );
  }
  
}

export default Card

In one of my web app's page I have added two cards, and I space them out with flex display.在我的 web 应用程序页面之一中,我添加了两张卡,并用柔性显示将它们隔开。

The page render:页面渲染:

function Home() {
    return (
        <div className={style.container}>
            <Card> </Card>
            <Card> </Card>
        </div>
    )
}

Container CSS:集装箱 CSS:

.container {
    width: 100vw;
    height: 100vh;
    margin-top: 10px;
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;

}

The only problem with this code is that the margin-top in the css is not applying margin to the div.此代码的唯一问题是 css 中的 margin-top 没有对 div 应用边距。 I encountered this problem several times, leading me to not be able to use nor padding nor margin.我多次遇到这个问题,导致我无法使用或填充或边距。 Can someone help?有人可以帮忙吗? Thanks.谢谢。

Image of components not being affected by margin不受边距影响的组件图像在此处输入图像描述

I found out that trying to reset React's default padding through the following lines of code:我发现尝试通过以下代码行重置 React 的默认填充:

* {    
    margin: 0 !important;
    padding: 0 !important;
}

was yielding the issue.正在解决这个问题。 Nonetheless, how can I reset React's default padding / margin without the styling affecting ALL padding and margins in the app?尽管如此,如何在不影响应用程序中所有填充和边距的样式的情况下重置 React 的默认填充/边距?

在此处输入图像描述

It's generally a bad idea to override the style properties for a lot of elements (the * selector).覆盖许多元素(* 选择器)的样式属性通常是个坏主意。 But, it is ok to override the user agent stylesheet for specific tags.但是,可以覆盖特定标签的用户代理样式表。 For instance, Chrome automatically adds a margin to the <body> tag, so you can override the margin property without using !important in React I think .例如,Chrome 会自动为<body>标签添加边距,因此您可以覆盖边距属性,而无需在 React 中使用!important我认为

After you remove the !important overrides, create a separate container class for your Card component.删除!important覆盖后,为您的 Card 组件创建一个单独的容器 class。 Setting widths and heights of individual flex items can interfere with the flex container layout, and possibly cause margins to collapse.设置单个弹性项目的宽度和高度可能会干扰弹性容器布局,并可能导致边距折叠。

you have to change display to block!!!您必须将显示更改为阻止!

Add a padding to container向容器添加填充

.container {
    padding: 10px;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM