Steven Yong Steven Yong - 5 months ago 19
CSS Question

MVC5 Adding glyphicon next to EditorFor

This is driving me a bit crazy adjusting the desired width to the glyphicon I have added next to a EditorFor textbox.

I have the below which I added a glyphicon next to the EditorFor, notice I initially put

.col-md-10
which is the default generated by MVC5 View template:

<div class="form-group">
@Html.LabelFor(model => model.ContactedDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10 input-group">
@Html.EditorFor(model => model.ContactedDate, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
<span class="btn btn-default input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
@Html.ValidationMessageFor(model => model.ContactedDate, "", new { @class = "text-danger" })
</div>
</div>


And it looks like this, notice the glyphicon is so far away:

enter image description here

I later change the
.col-md-10
to
.col-md-4
which become the below:

enter image description here

Still some distance away and when I use
.col-md-3
, it will overlap with the box:

enter image description here

What's more is when I adjust the width of the browser, the glyphicon will just moves to the position like the 1st screenshot when I use
.col-md-4
or
.col-md-3
, it's like it does not stick just next to the textbox.

I have also checked out this question here but it does not help me.

How do I add the glyphicon properly?

Answer

A new ASP.NET MVC project comes with a Site.css stylesheet. The rule that causes the issue is the one below that makes all <input> have a max-width:280 and that messes up your .input-group:

input,
select,
textarea {
    max-width: 280px;
}

You can change the above rule to include the .input-group and have the following:

input,
select,
textarea, 
.input-group {
    max-width: 280px;
}

Edit: This CSS also breaks the .form-block class of Bootstrap, so you will need the following rule as well.

input.form-block,
select.form-block,
textarea.form-block {
max-width: none;
}