John Doe John Doe - 1 month ago 14
CSS Question

Javascript function, trying to create a link and set its alignment

Alright, so to start with let's look at this:

function displayResult() {
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.style.cssText = "text-align:center;"
a.href = "http://example.com";
document.body.appendChild(a);
}


This is run from a button click, but when it creates the new link it isn't aligned to the center. I'm not sure why, and I was hoping to get some help.

Answer

To see the centered text effect, you need to make your link tag a block element, as the text-align property will only apply to block level elements (a tags are per default inline). You can either use camel cased CSS attributes, e.g. Javascript: textAlign for CSS: text-align:

a.style.display = "block";
a.style.textAlign = "center";

Here is a working example:

function displayResult() {
  var a = document.createElement('a');
  var linkText = document.createTextNode("my title text");
  a.appendChild(linkText);
  a.title = "my title text";
  a.style.textAlign = "center";
  a.style.display = "block";
  a.href = "http://example.com";
  document.body.appendChild(a);
}
<button onclick="displayResult()">Click</button>

Or you can also use the cssText property (thanks for mentioning in the comments):

a.style.cssText = "text-align:center; display: block;";

function displayResult() {
  var a = document.createElement('a');
  var linkText = document.createTextNode("my title text");
  a.appendChild(linkText);
  a.title = "my title text";
  a.style.cssText = "display:block; text-align:center;";
  a.href = "http://example.com";
  document.body.appendChild(a);
}
<button onclick="displayResult()">Click</button>