Search code examples
htmlcalc

Using calc() for width of div doesn't seem to work


I am trying to have a text input and two buttons in the same row. The length of the text input should be maxed out so that everything still fits in a row:

<div style="display:flex; flex-flow:row nowrap; align-items:center; justify-content:space-between; width:100%;">
    <!-- div style='width:calc(~"100% - 150px")' -->
    <div style='width: calc(50% - 120px);'>
        <SfTextBox FloatLabelType="@FloatLabelType.Never" Placeholder='' Value=@WatermarkID() Enabled="false"></SfTextBox>
    </div>
    <div><SfButton Type="button" Content="Edit..." @onclick="EditWatermark" IsPrimary="false"></SfButton></div>
    <div><SfButton Type="button" Content="Remove..." @onclick="RemoveWatermark" IsPrimary="false"></SfButton></div>
</div>

This is the result (with Google Chrome):

Screenshot

If I give the div e.g. a width of 50% (style="width:50%;"), the div's width gets set as desired. The above code shows another attempt to call calc in the commented out line, which didn't work either.

What do I have to do to get the desired result (text input as long as possible with buttons to its right), and why doesn't calc seem to work here?


Solution

  • If you want both buttons pushed to the right and the input field taking up all of the available space left, you can use flexbox (what you're already using):

    Remove the justify-content: space-between property (it's not needed anymore) and set the width of your input field to 100%. The buttons need the property flex-shrink: 0; so they won't get shrinked.

    Working example:

    <div style="display: flex; width: 100%;">
      <div style="height: 30px; background: orange; width: 100%;"></div>
      <button style="flex-shrink: 0;">Hello</button>
      <button style="flex-shrink: 0;">World</button>
    </div>

    If you want some spacing between the elements, you an use the gap property on the flex container, e.g. gap: 10px;.