I have a button, which is flexcontainer with two items.
.flex-container {
display: flex
column-gap: 1rem
align-items: center
margin-right: 10rem /* just for illustration sake */
cursor: pointer
&:hover
opacity: 0.6
}
And it takes all available space in a row despite the fact that the items wouldn't stretch. The problem is that when user points to the right from the button it reacts just like if the mouse would be on the button. I would like flexbox container to end right after the 2nd item. How it do it?
margin-right: auto
doesn't work
CodePudding user response:
You could use width: max-content
on the flex container. That will make the container's width match its contents.
This is similar to gavgrif's answer, but this will not establish an inline formatting context. That may or may not matter for your use case.
CodePudding user response:
Try using display: inline-flex
which will make it a flex container that renders like an in line element.
UPDATE: - I have added a demonstration of the outcome of the two types of flex display. The important thing to realise is that the flex behaviour is on the children of the flex-container and there is no difference in their layout between the two types of flex.
The difference is on how the parent container renders in relation to the surrounding page content. With display: flex
-the container is rendered as a block level element that has flexed children elements. With display: inline-flex
-the container is rendered as an inline level element that has flexed children elements.
.flex-container {
display: flex;
align-items: center;
border :solid 1px red; /* just for illustration sake */
cursor: pointer;
padding: 0 8px;
}
.inline-flex-container {
display: inline-flex;
align-items: center;
border:solid 1px blue; /* just for illustration sake */
cursor: pointer;
padding: 0 8px;
}
.caret {
width: 0;
height: 0;
border-style: solid;
border-width: 5px 5px 0 5px;
border-color: #000000 transparent transparent transparent;
display: inline-block;
margin-left: 6px;
top: 0;
position: relative;
}
<p>Display: flex (causes a block-level parent container and flexed children)</p>
<div class="flex-container">
<button type="button">Button</button>
<span class="caret"></span>
</div>
<hr/>
<p>Display: inline-flex (causes an inline-level parent container and flexed children</p>
<div class="inline-flex-container">
<button type="button">Button</button>
<span class="caret"></span>
</div>