Styling Divs

Divs are block-level elements, meaning they fill the page edge-to-edge. If this isn’t necessarily what we want, we can easily force changes to the div itself, and how it relates to the elements inside.

Changing Width

You can easily change the width of a div from 100% using the width property. Width values can be in percentages (changing) or pixels (unchanging). For example:

  • to be half of the page at any size of the brower window, set to width: 50%;
  • to be 300 pixels wide no matter the size of the browser window, set to width: 300px;
HTML
.a-class {
  width: ;
}

Centering on the Page

Have a div less than full-page and want it placed in the middle? Add the margin property, set to auto (margin: auto).

HTML
.a-class {
  margin: auto;
}

Cushioning From the Edge

Text inside of a div will set right aside its edges. To override this and give the text some “cushion” for easier-reading, add the padding property. Pixel values are best-suited here.

HTML
.a-class {
  padding: ;
}

Example

See how you can style divs into interesting content blocks using width, margin: auto, and padding!