【问题标题】:How to display the contents inside a div using flexbox如何使用 flexbox 在 div 中显示内容
【发布时间】:2020-08-22 12:59:04
【问题描述】:

我在我的第一个 react 应用程序中使用 flexbox 定位我的项目/卡片时遇到了麻烦。

我在卡片中放了一个 div(参见 Card 组件),然后放了一个 display: flex;但似乎我的输出中的每张卡片都像一个块(类似列),它只弯曲我的内容,而不是卡片的每个 div,我想要的是我的 div 是一行。

我也尝试了 flex-direction,但没有任何反应,知道如何制作这些家伙吗?

//My code in my Main//

const data = [
  {id: 1, t: 'Card-1',  description: 'This is a Card-1'},
  {id: 2, t: 'Card-2', description: 'This is a Card-2'},
  {id: 3, t: 'Card-3', description: 'This is a Card-3'},
  {id: 4, t: 'Card-4', description: 'This is a Card-4'},
  {id: 5, t: 'Card-5', description: 'This is a Card-5'},
]

function Main () {
return (
<div>
<div className="main-container">

          {data.map(d => {
          return (
              <Card 
                key = {d.id}
                title = {d.t}
                description = 
{d.description}
              />
              )
          })}
          </div>  

</div>)

export default Main;


//end of my Main//

// My code in my Card //

import React from 'react';
import './style.css';

function Card ({ title, description }) {
  return (
  <div className="items">

      <h2>{title}</h2>
        <p>{description}</p>

  </div>
)
}

export default Card;
//

//The style.css of my Card //

div.items {
  display: flex;
  border: 2px solid darkgreen;
  margin: 15px;
  max-width: 250px;
  min-height: 200px;
  background-color: deeppink;
  flex-direction: column;
}

div.items h2 {
  flex: 1;
  text-align: center;
}

div.items p {
  flex: 1;
  text-align: center;
}

//ends here

【问题讨论】:

  • 寻求代码帮助的问题必须包含最短代码以便在问题本身中包含重现它所必需的最好是Stack Snippet。见How to create a Minimal, Reproducible Example
  • ...但如果您不想要列,请删除flex-direction: column;
  • 如果你想让卡片彼此相邻,你需要在“行”元素(容器)上显示 flex
  • 对不起,我不知道它是堆栈溢出的新功能。我把我所有的代码都放在那里,因为我认为这都是必要的。感谢您的提示!
  • 当我尝试 display:flex 时它们并不相邻。

标签: javascript css reactjs flexbox css-position


【解决方案1】:

我只是在主容器中放了一个弹性显示:

.main-container{
  display: flex
}
.div-1 {
  flex: 1 //depends on your taste
}

【讨论】:

    【解决方案2】:

    您是否希望所有卡片连续显示,并且卡片内的内容必须是列中唯一显示的内容,我错了吗? 如果只是这样:

    .main-container {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;
    }
    

    【讨论】:

    • 我试试这个,但它们是列类型的。我希望他们彼此相邻。我尝试了 flex direction:column 但它仍然是一样的。
    • 你能做到jsfiddle.net 吗?至少我们可以帮助你,看看你做错了什么
    • 我的意思是我希望我的卡片像照片库类型。挨着坐。我尝试了您的代码,但不幸的是它显示列先生。
    • 大声笑你没有回答我的主要问题:你能做一个 jsfiddle 吗?如果您向我们展示那部分代码,至少我们可以为您提供帮助
    • 我的错误。好的,我会试试的。没有听说过 jsfiddle,但我会看到它,以便我可以向您展示先生。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多