'Elements Not Centering
I am making a website for a client of mine, but I have a problem. I want 3 buttons with text pop up but they won't center. When I checked the inspector I could see a weird margin right while I have not done this myself.
Thank you for all the replies, but sadly non of them worked. I think it has something to do with something else on my website.
It might be this: Photo Problem 2.
If you want code of a specific section, just say it I do not know what not to and what to put in here in terms of code.
#Buttons
{
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
text-align: center;
min-height: 400px;
margin: 0 auto !important;
}
.Button
{
margin-right: 50px;
width: 200px;
height: 200px;
background-color: white;
}
<div id="Buttons">
<div class="Button"></div>
<div class="Button"></div>
<div class="Button"></div>
</div>
Solution 1:[1]
To center the flex items, apply justify-content: center
to the container.
And to set the margin of the last button to 0, add this rule:
.Button:last-child {
margin-right: 0px;
}
Edit/note: I made the buttons smaller for the snippet below to not extend the width of the snippet window.
#Buttons {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
text-align: center;
min-height: 400px;
margin: 0 auto !important;
background: blue;
}
.Button {
margin-right: 50px;
width: 140px;
height: 140px;
background-color: white;
}
.Button:last-child {
margin-right: 0px;
}
<div id="Buttons">
<div class="Button"></div>
<div class="Button"></div>
<div class="Button"></div>
</div>
Solution 2:[2]
Set margin
to auto
.
.Button {
margin: auto;
width: 200px;
height: 200px;
background-color: white;
}
Code sandbox => https://codesandbox.io/s/html-code-editor-forked-f17y2?file=/style.css
Solution 3:[3]
I removed the 50px right margin in .Button
and used gap
in #Buttons
to set the "minimum gutter" spacing of the elements:
#Buttons {
display: flex;
flex-direction: row;
justify-content: space-evenly;
gap: 1em;
align-items: center;
text-align: center;
min-height: 400px;
margin: 0 auto !important;
border: 1px solid blue;
}
.Button {
width: 200px;
height: 200px;
background-color: white;
border: 1px solid red;
}
<div id="Buttons">
<div class="Button">A</div>
<div class="Button">B</div>
<div class="Button">C</div>
</div>
Solution 4:[4]
I had a similar problem. I had the button centered, then upon reopening, buttons left aligned even though I did not change anything. the display:flex; keywords fixed the issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Amila Senadheera |
Solution 3 | |
Solution 4 | StephenC |