我正在尝试了解 React 中边距的一些功能,并且仍然是 React 的新手。目前,我有一个包含一些 JSX/HTML 的 render
方法。我正在尝试使用 CSS 来更好地设计它的样式,但对代码有一些疑问。
- 在 CSS 中,我使用带有
Margin: auto;
的Buttons
将容器NavBar
中的元素居中,但它不起作用。但是,当我在.NavBar
中使用text-align
时,它就起作用了。这是为什么?我认为它会在 Buttons 中工作,因为它会相对于其父容器居中 ->NavBar
。
2.在 .NavBar
中,当我有高度 20%
时,它不会改变,除非我以像素为单位进行硬编码。由于 NavBar 是主要 App.js
的子项,它不会相对于 App 文件工作吗?
应用程序.js:
import React from 'react';
import {NavBar} from './NavBar/NavBar';
function App() {
return (
<div className="AppMain">
<NavBar/>
</div>
);
}
export default App;
应用程序.css:
.AppMain{
height: 100%;
}
导航栏.js:
import React from 'react';
import './NavBar.css';
export class NavBar extends React.Component{
render(){
return(
<div className="NavBar">
<button className="Buttons">About</button>
<button className="Buttons">Contact</button>
<button className="Buttons">Info</button>
<button className="Buttons">Home</button>
</div>
)
}
}
导航栏.css:
.NavBar{
background-color: black;
height: 20%;
}
.NavBar .Buttons{
margin-right: 20px;
margin-left: 20px;
text-align: center;
margin:auto;
}
最佳答案
您需要添加一个 <div>
将所有按钮包裹在一起,然后将 margin: auto;
放在一起在那div
, 你可以删除 margin:auto;
从按钮。
希望对你有帮助
关于html - 为什么 react 中的边距无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57404509/