html - 在 React 中使用 Flex 创建侧边栏但将内容居中

标签 html css flexbox

我正在尝试创建一个带有页眉和侧边栏的 UI。

我的 App 组件看起来像

class App extends React.Component {
  render() {
    return (
      <div>
        <Header />
        <div className="App">
          <SubHeader/>
          <Container className="container-comp"/>
        </div>
      </div>
    );
  }
}

App 的样式是

.App {
  height: 100%;
  display: flex;
}

和我的 SubHeader 是侧边栏的样子

const SubHeader = () => {
    return (
        <div id="sidebar">
            <div className="logo-container">
            </div>
        </div>
    );
}

sidebar 样式在哪里

   #sidebar {
     width: 12em;
     background: #39393b;
   }

这看起来像(请忽略钢笔涂鸦)

enter image description here

我想将侧边栏保持在该位置,但想将我的组件(控制台)居中。

我试过

.App {
  height: 100%;
  display: flex;
  justify-content: center;
}

enter image description here

但它居中包括侧边栏在内的所有内容。

我怎样才能让它工作?

谢谢

渲染

class Container extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        return (
            <div className={this.props.className}>
                <h3>Show Console</h3>
                <ServerCard />
                <RouterCard />
                <CommandCard />
                <LocationCard />
                <div>
                    <Button
                        className="submit-button"
                        onClick={this.runCommands}>
                        Submit
                    </Button>
                </div>
                <div>
                    {this.renderStatus()}
                    {this.renderLoc()}
                </div>
            </div>
        );
    }
}

最佳答案

SubHeader 组件包含在 .App 中。因此,将任何 CSS 应用于 .App 也将应用于 SubHeader 组件。

如果你只想让 Container 组件的元素居中,你需要将 CSS 应用到 .container-comp 就像,

.container-comp{
   text-align:center;
}

更新

看起来 Container 是您的自定义组件,例如 SubHeader 组件。您需要将作为 props 传递的类名 container-comp 分配给 Container 组件的父 div,如下所示,

const Container = (props) => {
    return (
        <div className={props.className} >  // here props.className = container-comp
            <div>
              console
            </div>
        </div>
    );
}

更新 2

当您使用 display:flex 时,您的自定义 Container 组件不会占用可用空间。您只需添加 flex-grow:1 即可占用全部可用空间。

.container-comp{
   text-align:center;
   flex-grow: 1;
}

Demo

关于html - 在 React 中使用 Flex 创建侧边栏但将内容居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57438078/

相关文章:

css - 图像以 Firefox 为中心,但在 Chrome 上被截断

html - 嵌套 Flexboxes 中图像的奇怪行为

javascript - 变量未在函数链末尾更新

html - CSS Hover div 对无子 div 的触发效果

javascript - 从 iframe 显示弹出窗口并调暗背景,包括父页面

javascript - 为什么 document.querySelector 不适用于伪元素?

html - 如何在 Twitter Bootstrap 中以表单形式创建图像按钮?

html - 一个 div 推另一个 div

CSS 媒体查询图像加载

html - 如何使两个堆叠的div具有相同的高度