1

I want to write the viewport width into a div inline style like so.

<div style="width:[viewportwidth]">stuff here</div>

The inline style should change as the viewport changes i.e. if I adjust the browser width, the style will change accordingly, in real-time.

I have some js that writes the viewport, but it requires an ID for document.write and thus some HTML element with that ID. I cannot figure out how to just get the viewport width in real time as the value so it can be used in a style.

1 Answer 1

1
window.addEventListener('resize', function(event){
  var viewportWidth = this.outerWidth;
});

Then you can just apply the viewportWidth variable to the div's style attribute.

However, this would probably be better done with CSS vw units.

div{
   width:100vw;
}

This is 100% the viewport width.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.