Home > Enterprise >  Why are appended bootstrap buttons not spaced properly?
Why are appended bootstrap buttons not spaced properly?

Time:05-20

I am currently attempting to use jQuery to append multiple buttons to a bottom of a form. In an attempt to keep my code somewhat clean, I am using document.createElement() statements to add the items to the form, like so :

//Form-footer is a container of buttons on the end of the form.
$("#form-footer").append(        
        $(document.createElement('button'))
        .prop({
            class: "btn btn-success",
            id: "save-button"
        })
        .html("Save")
    )
        .append(
         $(document.createElement('button'))
            .prop({
                class: "btn btn-secondary",
                id: "preview-button"
            })
            html("Preview Report")
    )

However, I noticed a styling issue : My buttons end up squished together, without the margin in between them.

enter image description here

I was able to discover the cause of the styling issue. While the development console may show that the items are in new lines and indented properly....

Tag indentation looks fine in the developer console...

...They actually lack both, as can be revealed by 'Edit as Html':

Usage of 'Edit as HTML' reveals improper indentation.

Manually editing this HTML to add new lines and indentation in Chrome's developer console fixes the styling issue, but that's obviously not helpful in production applications.

Why doesn't append add new lines for elements? What do I need to do to get appended tags to have proper new lines in their parents?

CodePudding user response:

Why does it happen?


By my understanding, the $(document.createElement('div'))... is processed by the containing .append as a string, or at least, it behaves similarly enough for this answer's purpose.

.append() will, in essence, concatenate the contents of the parent tag and the input into a long, single string.

How can it be fixed?


Because of that, a newline character doesn't get inserted between the appended elements. To insert the newline and fix the styling, use .append('\n') before any buttons being appended after the first.

Why after the first? Inspect the question's HTML - the first button is already on a separate line.

$("#form-footer")        
  .append(
    $(document.createElement('button'))
      .prop({
        class: "btn btn-success",
        id: "save-button"
      })
      .html("Save")
  )
  .append('\n') //Append a new line
  .append(
    $(document.createElement('button'))
      .prop({
        class: "btn btn-secondary",
        id: "preview-button"
      })
      .html("Preview Report")
  )

Fixed buttons

fixed HTML

CodePudding user response:

Change this:

class: "btn btn-success"

to this:

class: "btn btn-success ml-1"

and you should be good to go.

By default there is no margin on buttons in Bootstrap.

  • Related