I'm trying to put 2 components side by side but I would like one of components to be on the right of the other component without the other component being reorientated. Example:
Here, after adding a button component to the side of the "Function" heading, the "Function" heading gets pushed to the left. However, I would like the "Function" heading to be in the middle and the "TEST" at the right. As much as possible, I'd like to avoid absolute positions.
<h4 align="right" style={{display: "inline-block"}}>Function</h4><Button sx={{float: "right"}}>Test</Button>```
This is my current code but I'm unsure what I can do. Thanks in advance!
CodePudding user response:
Your question is not very clear to me, but I believe you should read about flex layout CSS property.
All possible solutions of your question
.flex0 {
display: flex;
align-items: center;
justify-content: space-between;
}
.flex1 {
display: flex;
align-items: center;
justify-content: space-around;
}
.flex2 {
display: flex;
align-items: center;
justify-content: space-evenly;
}
<div >
<h4 align="right" style={{display: "inline-block"}}>Function</h4><Button sx={{float: "right"}}>Test</Button>
</div>
<div >
<h4 align="right" style={{display: "inline-block"}}>Function</h4><Button sx={{float: "right"}}>Test</Button>
</div>
<div >
<h4>Function</h4><Button>Test</Button>
</div>
CodePudding user response:
.flex-container {
display: flex;
}
.flex-child {
flex: 1;
border: 2px solid yellow;
}
.flex-child:first-child {
margin-right: 20px;
}
<div >
<div >
Flex Column 1
</div>
<div >
Flex Column 2
</div>
</div>
CodePudding user response:
There are many ways to accomplish this. But first you must understand why this misalignment happens when you use float
.
Without float
on button you can see it perfectly aligns to the heading with inline-block
; but as soon as you introduce the float, it detaches the button as pushes it on the right side of the screen on the top corner of the block line. (image attached)
This happened because the heading tags, by default, have margins.
So to align them properly,
1st thing you can do is to provide the float
button a similar margin as that of the heading.
<div>
<h4 style='display: inline-block;'>Function</h4>
<Button style='float: right; width: 50px; height: 30px; margin: 1.33em'>Test</Button>
</div>
2nd:
Wrap them in a div and use a grid
with align-items: center
<div style='display: grid; grid-template-columns: 1fr 1fr; align-items: center;'>
<h4 style='display: inline-block;'>Function</h4>
<Button style='margin-left: 85%; width: 50px; height: 30px;'>Test</Button>
</div>
3rd
going the usual way, introduce left margin to the button in % (or vice-versa) i.e without float
<div>
<h4 style='display: inline-block;'>Function</h4>
<Button style='margin-left: 75%;'>Test</Button>
</div>
<div>
<h4 style='display: inline-block; margin-right: 85%;'>Function</h4>
<Button style=''>Test</Button>
</div>
Other options:
Utilise flex containers as suggested by other answers.