Skip to content

CSS Sizing

Controlling the size of elements is fundamental to CSS layout. The width and height properties are used to set the width and height of an element. CSS provides a variety of units and methods for precise sizing control.

width and height

These two properties are used to set the width and height of an element.

css
div {
  width: 500px;
  height: 200px;
  border: 1px solid black;
}

You can use various units:

  • auto: (Default) The browser calculates the width and height automatically. For block-level elements, the width is usually 100% of their parent container; for inline elements, the width is determined by the content.
  • px (Pixels): An absolute unit providing precise pixel-level control.
  • % (Percentage): A relative unit, relative to the width or height of its parent element.
  • em / rem: Units relative to font size.
  • vw / vh (Viewport Units): Relative to the width and height of the viewport (browser window). 100vw equals the viewport width, 50vh equals half the viewport height.
css
.full-width {
  width: 100%;
}

.half-screen-height {
  height: 50vh;
}

min-width and max-width

These properties are used to set a minimum and maximum limit on an element's width. This is very useful in responsive design to prevent elements from becoming too narrow on small screens or too wide on large screens.

  • min-width: Sets the minimum width of the element. Even if there is little content or the parent container is narrow, the element's width will not be less than this value.
  • max-width: Sets the maximum width of the element. Even if there is a lot of content or the parent container is wide, the element's width will not exceed this value.

A common application is to create a centered page container with a maximum width limit:

css
.container {
  max-width: 960px; /* On large screens, content area won't exceed 960px */
  min-width: 320px; /* On small screens, container won't be narrower than 320px */
  width: 90%;       /* On medium screens, width is 90% of parent container */
  margin: auto;     /* Horizontally centered */
}

min-height and max-height

Similar to width, min-height and max-height are used to limit the height of an element.

  • min-height: Sets the minimum height of the element. Often used to ensure the footer sticks to the bottom when content is sparse.
  • max-height: Sets the maximum height of the element. Often used in conjunction with overflow: auto; to create an area that scrolls when content exceeds the limit.
css
.card-content {
  max-height: 300px;
  overflow-y: auto; /* Vertical scrollbar appears if content height exceeds 300px */
}

.main-wrapper {
    min-height: 100vh; /* Ensure main content area is at least as tall as the screen */
}

By flexibly using these sizing properties, you can create layouts that are both beautiful and adaptable to different devices.

Content is for learning and research only.