Curriculum
Course: CSS
Login

Curriculum

CSS

CSS INTRODUCTION

0/1

CSS Selectors

0/1

CSS Comments

0/1

CSS Padding

0/1

CSS Box Model

0/1

CSS Combinators

0/1

CSS Pseudo-classes

0/1

CSS Pseudo-elements

0/1

CSS Dropdowns

0/1

CSS Image Gallery

0/1

CSS Image Sprites

0/1

CSS Counters

0/1

CSS Website Layout

0/1

CSS Specificity

0/1

CSS Math Functions

0/1
Text lesson

CSS Layout – width and max-width

Using width, max-width and margin: auto;

As discussed earlier, a block-level element naturally occupies the entire available width, extending to the edges on both sides.

However, setting a specific width for a block-level element confines it within that width, preventing it from extending to the container’s edges. By setting the margins to auto, you can horizontally center the element within its container. In this scenario, the element will occupy the designated width, and the surplus space will be evenly distributed between the two margins.

 

This <div> element has a width of 500px, and margin set to auto.

 

NOTE: When the browser window is narrower than the width of the element, the issue with the <div> mentioned above arises, resulting in the addition of a horizontal scrollbar to the page.

However, employing max-width instead in such circumstances enhances the browser’s management of smaller windows. This is particularly crucial for ensuring the usability of a website on smaller devices.

 

This <div> element has a max-width of 500px, and margin set to auto.

 

Tip: Adjust the width of the browser window to less than 500px to observe the contrast between the two divs!

Below is an illustration of the aforementioned pair of divs:

Example

div.ex1 {
  width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
}

div.ex2 {
  max-width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
}