Search code examples
csstwitter-bootstrapblazor-server-siderazor-components

How to align parent component elements with child component elements using bootstrap, razor reusable components and styling?


Just learning Blazor and razor pages. I am using bootstrap to style my pages. I would like to know how to handle this situation:

Parent references a child component. The Child component uses a label and a select list box. Using bootstrap I style the component like this:

<div class="row">
    <label for="@selectID" class="col-1 my-auto">Select a City:</label>
    <select ID="@selectID" class="form-control col-3" @onchange="OnSelectedCityChanged">
        @if (@CityList != null)
        {
            @foreach (var city in CityList)
            {
                <option value="@city">@city</option>
            }
        }
    </select>
</div>

This aligns the elements in the Child component nicely. However, in the parent, if I add anything inline behind the child conponent, the child component's styling is trashed. What if I want to add a message inline with the components. Can that be done? How can I do that? Here are some screen shots. enter image description here

And here is an attempt to add the 'Message' inline with the component: Parent's HTML:

<div class="row">
    <div class="col-4">
        <Cities @bind-SelectedCity="city" selectID="selCities" CityList=@cities></Cities>
    </div>
    <div class="col-1">Message</div>
</div>

And the image of the result: enter image description here

So it appears the Child component is taking up the entire line and getting squished when bootstrap grid is used in the parent. What can I do to fix this? I really do not want my reusable code to take up the entire line. I'm sure it's my lack of experience, but that's why I'm asking for help.

Thanks heaps!


Solution

  • Assuming you are using Boottrap 4.0 and above, probably this is what you are looking for (working representation).

    <div class="d-flex">
      <div class="form-group">
        <div class="d-inline-flex">
          <label for="@selectID">Select a City:</label>
          <select ID="@selectID" class="form-control">
            @if (@CityList != null)
            {
                @foreach (var city in CityList)
                {
                    <option value="@city">@city</option>
                }
            }
          </select>
        </div>
        <div>Message</div>
      </div>
    </div>