Reputation: 822
I'm trying to understand some functionality of margins within React and still newbie with react. Currently, I have a render
method that has some JSX/HTML. I'm trying to use CSS to style it better but have some questions regarding the code.
Buttons
with Margin: auto;
to center the elements within the container NavBar
but it is not working. But when I have text-align
in the .NavBar
it works. Why is that? I thought it would work within Buttons because it will center relative to its parent container -> NavBar
.2.In .NavBar
, when I have height 20%
for example, it does not change unless I hard code in pixels. Since NavBar is the child of the main App.js
, wouldn't it work in relative to the App file?
App.js:
import React from 'react';
import {NavBar} from './NavBar/NavBar';
function App() {
return (
<div className="AppMain">
<NavBar/>
</div>
);
}
export default App;
App.css:
.AppMain{
height: 100%;
}
NavBar.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>
)
}
}
NavBar.css:
.NavBar{
background-color: black;
height: 20%;
}
.NavBar .Buttons{
margin-right: 20px;
margin-left: 20px;
text-align: center;
margin:auto;
}
Upvotes: 2
Views: 14104
Reputation: 166
margin: auto;
only works if the width is specified and if the element is block-level. Look at this answer to understand how centering with margin: auto;
actually works.
The height doesn't work because you've set the height of the AppMain to 100% which will be calculated after everything is rendered onto the DOM. You're basically trying to calculate 20% of 100% of something that isn't calculated yet. Try explicitly setting the height of the AppMain and see what that does. Relevant answer link.
Upvotes: 1
Reputation: 359
The default display of the Button is inline-block. if you want to use margin: auto, You just need to change the display value to block
Upvotes: 0
Reputation: 4147
You need to add a <div>
that wraps all the buttons together and just put margin: auto;
on that div
, and you can remove the margin:auto;
from the buttons.
Hope this helps
Upvotes: 1