HTML
<div id="flexbox-container">
<h1 id="test1">test1</h1><h1 id="test2">test2</h1><h1 id="test3">test3</h1>
</div>
CSS
#flexbox-container {
display:inline-flex;
}
#test1 {
float:left;
}
#test2 {
justify-content:center;
align-items:center;
text-align:center;
align-self:center;
align-content:center;
}
#test3 {
position:relative;
left:1000px;
}
Why does test2 not center itself in the flex? I would prefer not to have to set px or margin to get it to centre. I tried all sorts of aligning stuff on it yet it still sticks to the left. I need the three items to be inline, so setting it to flex wouldn't work (though it does center align if I make it flex), PLEASE HELP IVE BEEN TRYING FOR DAYS
https://codepen.io/throwaway123/pen/mdpJJKY
CodePudding user response:
Only this much code is enough. No need for all those styles for separate h1
tags. You have to give the aligning styles to the parent div.
#flexbox-container {
width: 100%;
display:inline-flex;
justify-content: space-between;
}
<div id="flexbox-container">
<h1 id="test1">test1</h1>
<h1 id="test2">test2</h1>
<h1 id="test3">test3</h1>
</div>
CodePudding user response:
Basically that isn't how flex works.
You don't want the contents of the second item to be justified within itself, you want the container to have that element centered.
If you scrap all the positioning of the three items you can get flex to do the work for you. There are several ways of telling it how you want the items set out in the line. For example justify-content: space-between
.
From MDN:
The items are evenly distributed within the alignment container along the main axis. The spacing between each pair of adjacent items is the same. The first item is flush with the main-start edge, and the last item is flush with the main-end edge.
#flexbox-container {
display: inline-flex;
justify-content: space-between;
width: 100vw;
}
<div id="flexbox-container">
<h1 id="test1">test1</h1>
<h1 id="test2">test2</h1>
<h1 id="test3">test3</h1>
</div>
CodePudding user response:
Using IDs for css is bad practice. I'd suggest you to start using class selectors
Anyway, here is solution to your problem :
<style>
#flexbox-container {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
}
</style>
CodePudding user response:
If you want the h1 tags centered too you can wrap the h1 tag by a div. Then you can assign the div text-align: center
CSS Property.
#flexbox-container {
background: green;
display:flex;
justify-content: space-between;
text-align: center;
}
#flexbox-container div {
width: 100%;
}
<div id="flexbox-container">
<div>
<h1 id="test1">test1</h1>
</div>
<div>
<h1 id="test2">test2</h1>
</div>
<div>
<h1 id="test3">test3</h1>
</div>
</div>