JSG
JSG

Reputation: 430

Set a css property to screen width using css

Is there any way to set a css property to the screen width?

What I want to achieve is something close to this:

div{width: screen width; }

Or

.divTest{width: screen width; }

Edit 1: I would like to use the class to exactly size other elements with the current width as i choose with css.

Edit 2: I don't believe it can be done without scripting of some sort but what do I know.

Edit 3: Final Thoughts A post about the widow re-sizing script using JavaScript is here in Alex V's answer. You'd just add in the script flavor you want. In my case it'd be setting a class property. However I believe setting visual attributes with JavaScript can be bad practice/undesirable in certain uses.

Upvotes: 4

Views: 15123

Answers (3)

timolawl
timolawl

Reputation: 5564

Try width: 100vw; or as the above comment suggests, width: 100%;.

You may also want to set the meta tag in the HTML if it applies:

<meta name="viewport" content="width=device-width, initial-scale=1">

Edit:

If the <div> isn't fitting 100% of the screen width, perhaps you need to have the default margin/padding reset:

*, :before, :after {
    box-sizing: border-box; // habit
    margin: 0;
    padding: 0;
}

Upvotes: 5

Pbk1303
Pbk1303

Reputation: 3802

Viewport units for CSS

vw, vh
1vw = 1% of viewport width
1vh = 1% of viewport height

Sizing div based on window width

Upvotes: 2

Jon Falkenstein
Jon Falkenstein

Reputation: 135

Generally, a div, if it's set to display:block (which is the default in most browsers, I believe) will expand to the full width of it's parent. If you want it to be the full width of the screen, it really depends on the way your page is configured.

If the div is within another element that is only set to width:500px or any other size, the div will only be the width of the parent. But if div's parent is the html body, then it should be the full width of the screen.

I've been smacking my head around on html and css a lot lately, and the best tool I've found to figure out CSS issues like this is Chrome's developer tools. You can actually right-click and "inspect" the div you are looking at. Then you can try out all the different css settings you want and Chrome will show you in real-time what effect those things will have.

Upvotes: 3

Related Questions