Ask coding questions

← Back to all posts
How do i make a rectangle in CSS to cover the width of the screen?
AzureScripts (164)

I want to have a rectangle to go from the left side of the screen, to the right side of the screen.

vedprad1 (873)

By rectangle, if you mean div, you should write this in your style sheet:

div {
  width: 100%;

Or, if you are making a rectangle in canvas, do this in js:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.rect(0, 0, [Canvas Width], 100);

If this answers your question, please check the checkmark on the left side of this message. Thanks and Good Luck!

heyitsmarcus (315)

@vedprad1 It is a tad more complicated than just width: 100% because percentage is relative to the container of the div and also unless the div has content (or a height specified), this CSS will do nothing on the page.

What you can do to ensure you see a rectangle, regardless of where the element is declared on the page, is to use the following CSS on an element such as a div:

div {
  position: fixed;
  top: 0;
  left: 0;
  height: 80px;
  width: 100vw;
  background: dodgerblue;

The position fixed property will cause it to be a sticky rectangle that you can move around the screen with the top, bottom, left, and right properties. You must either have content inside the div itself or a height property for the rectangle to show up. Also, the vw unit is always relative to the viewport, so 100vw is the entire width of the window. Only use % if you know what you're doing; otherwise, you'll end up with strange behavior you weren't expecting.

Here's a repl of the behavior:

AzureScripts (164)

@heyitsmarcus Thanks for this. Maybe you could help me with another question?

How do i move a <p> so it is a bit more in the middle of the page?
You can see what i mean here

heyitsmarcus (315)

@AzureScripts if you use CSS Grid, you can easily center text within any other container. First, apply a display: grid to the parent container (in this case the div element). Then, apply display: grid to the p element and use CSS like so:

p {
  display: grid;
  justify-self: center;
  align-self: center;

/* any other styles as well */

justify-self will horizontally align the element and align-self will vertically align the element. If you set those to center, it will position the p exactly in the center of the div.

Here's a jsfiddle of it in action: