What is the best way to align a button directly beside an input field using Bootstrap's columns and grid system?

Is it possible to place a button right next to an input box while utilizing the bootstrap columns/grid system? The Label is set to 2, EditorFor div to 4, and the input div to 6. When I reduce the EditorFor div to 3, it moves the input/button div closer together, but also decreases the width of the EditorFor

The style

style = "border: 1px solid red;"
is used for debugging purposes.

View the current layout here

See an example of the EditorFor div set to 3 and shrinking the input width

<div class="form-horizontal">
        <div class="form-group">
            @Html.LabelFor(model => model.Tag.Name, htmlAttributes: new { @class = "control-label col-md-2", style = "border: 1px solid red;" })
            <div class="col-md-4" style = "border: 1px solid red;">
                @Html.EditorFor(model => model.Tag.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Tag.Name, "", new { @class = "text-danger" })
            </div>
            <div class="col-md-6" style = "border: 1px solid red;">
                <input type="submit" value="Add Tag" class="btn btn-default" style = "border: 1px solid red;"/>
            </div>
        </div>
</div>

Thank you

  • Additional information

Below is the HTML output:

<div class="form-horizontal">
        <div class="form-group">
            <label class="control-label col-md-2" for="Tag_Name" style="border: 1px solid red;">Tag Name:</label>
            <div class="col-md-4" style = "border: 1px solid red;">
                <input class="form-control text-box single-line" data-val="true" data-val-length="Tag cannot be longer than 50 characters." data-val-length-max="50" data-val-regex="Must start with a capital letter, only alphabetic characters and no spaces allowed." data-val-regex-pattern="^[A-Z]+[a-zA-Z&quot;&#39;\s-]*$" data-val-required="The Tag Name: field is required." id="Tag_Name" name="Tag.Name" type="text" value="" />
                <span class="field-validation-valid text-danger" data-valmsg-for="Tag.Name" data-valmsg-replace="true"></span>
            </div>
            <div class="col-md-6" style = "border: 1px solid red;">
                <input type="submit" value="Add Tag" class="btn btn-default" style = "border: 1px solid red;"/>
            </div>
        </div>
</div>

Answer №1

Utilize the input group feature to position a button right beside an input field.

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff9d90908b8c8b8b89f8fbeb6eabfb2bbbabdeedae4beaea7ba">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="form-horizontal">
  <div class="form-group">
    <label class="control-label col-md-2" for="Tag_Name" style="border: 1px solid red;">Tag Name:</label>
    <div class="col-md-4" style="border: 1px solid red;">
      <div class="input-group">
        <input class="form-control text-box single-line" data-val="true" data-val-length="Tag cannot be longer than 50 characters." data-val-length-max="50" data-val-regex="Must start with a capital letter, only alphabetic characters and no spaces allowed." data-val-regex-pattern="^[A-Z]+[a-zA-Z&quot;&#39;\s-]*$"
          data-val-required="The Tag Name: field is required." id="Tag_Name" name="Tag.Name" type="text" value="" />
        <span class="field-validation-valid text-danger" data-valmsg-for="Tag.Name" data-valmsg-replace="true"></span>
        <div class="input-group-append">
          <input type="submit" value="Add Tag" class="btn btn-default" style="border: 1px solid red;" />
        </div>
      </div>
    </div>
  </div>
</div>

Answer №2

One issue arises with @Html.EditorFor as it has a restricted maximum width, preventing it from expanding to the size of col-md-4 or larger. Therefore, the choices are either to widen the maximum width for @Html.EditorFor to fill the space of col-md-4, or utilize col-md-3 to bring the button closer to the input.

Opting for col-md-3 poses the challenge of causing the width of EditorFor to shrink in relation to subsequent instances of

EditorFor</code) because of the padding in Bootstrap's column/grid system.</p>
<p><a href="https://i.sstatic.net/zdI9s.png" rel="nofollow noreferrer"></a></p>
<p>To address this, eliminating the <code>padding-right
or setting it to 0 removes the gap and enables EditorFor to fully extend to the right side of the col.

https://i.sstatic.net/siiPY.png

Revised code snippet:

<div class="form-group">
    @Html.LabelFor(model => model.Tag.Name, htmlAttributes: new { @class = "control-label col-md-2", style = "border: 1px solid red;" })
    <div class="col-md-3" style="border: 1px solid red; padding-right:0;">
        @Html.EditorFor(model => model.Tag.Name, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Tag.Name, "", new { @class = "text-danger" })
    </div>
    <div class="col-md-7" style="border: 1px solid red;">
        <input type="submit" value="Add Tag" class="btn btn-default" style="border: 1px solid red;" />
    </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve data from dynamic controls using C#?

When loading the page, I dynamically create radio button list controls on my project. While trying to retrieve the value of the selected radio button chosen by the user, I encountered some difficulties. Since the radio buttons are created dynamically, I am ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...

Using regular expressions in PHP to identify HTML elements containing '<p>' that appear after the initial '<H1>' tag

Can you provide guidance on creating a Regular Expression in PHP to identify HTML <p> elements that come after the initial <H1> tag? Here's an example that checks for inequality with the expression: if(!preg_match_all('#<p(.*?)&l ...

What would be your approach to incorporating code highlighting while scrolling?

Is there a library available or what would be the best way to create a blog page with code highlighting similar to Stripe's documentation? I want the code on the page to highlight as the user scrolls, just like in the Stripe documentation. Any recomme ...

Why does the selected index event only trigger once when the index of the ListItem is changed?

Imagine an asp:dropdownlist that triggers the SelectedIndexChangedEvent based on the selection of a listitem index..... However, have you ever wondered why the event fails to trigger when selecting the same listitem index again.... ...

Obtaining added HTML content following an AJAX request using JQuery

After making an ajax request to append a new entry, everything seems to be working fine. However, I noticed that the design is not displaying correctly. Upon inspection, it seems that the HTML has been loaded properly, but for some reason accessing the dat ...

After inserting a new checkbox input, Chrome fails to automatically populate the fields with autofill

I have a login form on my website which includes fields for both email address and password. So far, all the browsers I've tested have been able to autofill these fields successfully. Recently, I decided to add a checkbox input to the form. However, ...

Selecting the initial and final elements in a list without utilizing pseudo-classes

Currently, I am in the process of designing a custom MUI styled component and I have encountered a challenge. I want to apply extra styles specifically for the first and last child elements. The issue arises because MUI utilizes the emotion styled library, ...

Failed PHP response when jQuery was called

I'm working on a project that involves two files: one PHP and one HTML. The HTML file acts as the user interface where users input their queries, while the PHP file handles the processing and events before returning the output back to the HTML file. I ...

Tips for ensuring the accurate retrieval of prop values by waiting for the value to be set

Encountering an issue with the .toUpperCase() method within one of my components, resulting in the following error: TypeError: Cannot read properties of undefined (reading 'toUpperCase') This problem seems to stem from a race condition in fetc ...

When PHP is connected to the database, Ajax remains inactive and does not perform any tasks

I am currently working on setting up a simple connection between JavaScript and my database using ajax and PHP. The goal is for JavaScript to receive a name from an HTML form, make changes to it, send it to PHP to check if the name already exists in the da ...

When a table row is selected, set the OnClick attribute of an input to the value of the TD cell in that row based on

I'm really struggling with this. So, here's the issue - I have a table where rows get assigned a class (selected) when clicked on. Now, there's an input inside a form that needs to redirect to another page when clicked, and it also needs t ...

Implementing dynamic CSS class addition on CodeIgniter web pages

Exploring the templating mechanism I use in my CodeIgniter application: public function index($page = 'login') { $this->load->view('admin/header',array('page'=>$page)); $this->load->view(&a ...

Does Ext js have a monochromatic theme of blue running through everything

While the blue color may give off a nice office ambiance, it's important to have variety in the appearance of different applications. Is it simple to customize the look in ext js? ...

Arrange and pile up 3 columns using Bootstrap 4

My project currently has a structure using bootstrap columns, as shown in the image below: https://i.sstatic.net/JufaU.png However, I need to change to a lower resolution and rearrange the columns like this: https://i.sstatic.net/IB9sY.png I came acr ...

Having trouble getting smooth scrolling with easing to function properly

I'm facing an issue with a JQuery function that is supposed to enable smooth scrolling using JQuery easing, but for some reason, it's not functioning correctly and I'm unable to pinpoint the error. Here is the code for the function: $(func ...

Showing the computation outcome on the identical page

I have implemented a table within my PHP code. In the second column of this table, it typically displays "---". However, once I click the submit button, the same page should now display the calculated result. Here is an example: <table> <tr>& ...

Creating an animated link with a dynamic underline featuring a trio of vibrant colors

I'm having trouble figuring out how to animate my links on hover with 3 different colors. I attempted using the linear-gradient property but it doesn't seem to be working. Any suggestions on how to proceed? Below is an example of what I'm a ...

Rotating SVG graphics with a growth effect

Check out my CSS below: /* -------------------------- Base --------------------------- */ body { padding-top: 60px; background: #0f4e7a; } svg { margin: auto; display: block; width: 28%; } .star{ fill: #FFF; } /* ------------------ ...

Dropdown selection triggers an Ajax request

I have encountered an issue while attempting to make an Ajax request to the page chosen in a drop-down menu. While most of my script code works fine in binding a mouse click to table rows, it seems to fail in this particular scenario. The error message I r ...