0

I am trying to center an iframe by wrapping it in center tag using javascript i tried below script but its not working

<iframe id="xiframe" class="xiframe" src="https://www.w3schools.com" title="W3Schools Free Online Web Tutorials">

I used following script which is not working

function wrap(el, wrapper) {
        el.parentNode.insertBefore(wrapper, el);
        wrapper.appendChild(el);
    }
    
    // example: wrapping an anchor with class "wrap_me" into a new div element
    wrap(document.querySelector('xiframe'), document.createElement('center'));

I had tried css solution before that didn't work.

iframe {
  display:block;
  border: 3px dotted;
  width: 300px;
  height: 300px;
  align:center;
}

There are question raised on stackoverflow but those solution are not working. Only working solution so far is when i manually wrap iframe in center tag

<center><iframe id="xiframe" class="xiframe" src="https://www.w3schools.com" title="W3Schools Free Online Web Tutorials"></center>

i want to achieve same using JavaScript

Learning
  • 19,469
  • 39
  • 180
  • 373
  • 1
    Your information is very, very outdated (and unhelpful): W3Schools.com is not an authoritative resource and is full of bad advice (that site alone is responsible for _so many_ SQL injection vulns) - but anyway: _the `
    ` element has been obsolete in HTML for over 23 (25?) years_. You should be using CSS instead.
    – Dai Mar 27 '23 at 04:16
  • `document.querySelector('xiframe')` will return the first element `` _which isn't a thing_ - instead, what you want is `document.getElementById('xiframe')` or `document.querySelector('#xiframe')`. – Dai Mar 27 '23 at 04:17
  • Also, there is no `align: center;` property in CSS. (The `text-align:` property controls inner flow content's text justification, while `align-items` only affects `flex` and `grid` children, neither of which apply in this situation. Furthermore, ` – Dai Mar 27 '23 at 04:19
  • ...aaaaaand your `` tag. [The ` – Dai Mar 27 '23 at 04:20
  • @dia, at this point i am looking for a quick solution and i agree with you what you said. i had tried CSS solution that doesn't seems to work. can you suggest what is best solution as per latest standards – Learning Mar 27 '23 at 04:21
  • @dia i had tried `text-align:center` that doesnt work, so i left it as it as i tried so many options – Learning Mar 27 '23 at 04:23
  • 1
    Just do `` - this works because [using `auto` for left and right margins will horizontally center a fixed-width block element](https://stackoverflow.com/questions/963636/why-cant-i-center-with-margin-0-auto). – Dai Mar 27 '23 at 04:23
  • @dia, my mistake closing iframe i must have delete it when trying different things – Learning Mar 27 '23 at 04:24
  • Can you add this to solution so that i can mark it as correct solution as it will help others in future also. – Learning Mar 27 '23 at 04:27

0 Answers0