我正在尝试创建一个带有页眉和侧边栏的 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;
}
这看起来像(请忽略钢笔涂鸦)
我想将侧边栏保持在该位置,但想将我的组件(控制台)居中。
我试过
.App {
height: 100%;
display: flex;
justify-content: center;
}
但它居中包括侧边栏在内的所有内容。
我怎样才能让它工作?
谢谢
渲染
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;
}
关于html - 在 React 中使用 Flex 创建侧边栏但将内容居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57438078/