Typically, any block-level element uses all the available space to place an element in a container and stretches itself to fill it. However, we might not want this to happen because we may lose our control while working with a small screen.
CSS allows us to set layouts using width
and max-width
features to have more control over the element’s placement and spreading.
width
and max-width
width
propertyThe width
property allows us to set a specific width of the element, allowing it to expand to that size.
width: auto or initial or specific value(50%, 50px, etc) or inherit;
auto
: This is a default value and depends on the size of the browser. initial
: This is a keyword that is used to set any CSS property to its default value.specific value
: This would be any number that you would write with the px
, cm
, %
, and more. This value will dictate the element to have this amount of width.inherit
: This is a keyword that tells the property of an element to inherit its value from the parent element.Note: Using the width property alone may lead to an issue while working with small or different screen sizes. If you have specified any value for the width and the screen size changes, it will automatically add a scroll bar for that element.
max-width
propertyThe max-width
property allows us to set a boundary or a limit for the element. This property will restrict the component to not exceeding a particular value in any case.
The max-width
property makes elements more attractive and presentable when moving to small screens.
max-width: none or initial or specific value(50%, 50px, etc.) or inherit;
none
: By default, there is no max-width
for the elements. Therefore, none
represents that value.initial
: This is a keyword that is used to set any CSS property to its default value.specific value
: This is any particular value that we'll write with px
, cm
, %
, and more. This value would dictate that the element should not exceed the maximum width value.inherit
: This is a keyword that tells the property of an element to inherit its value from the parent element.style
tag.widthExample
, for div
. Inside the class, the width
property is assigned a value of 600px, along with auto margins and some aesthetics to beautify div
.max-widthExample
, for div
. The max-width
property is assigned a value of 600px along with auto margins and some aesthetics to beautify div
.style
tag before the head
tag.div
tag, we add our class widthExample
. This class will add colors to the div
tag and the width
property value. This div
will now expand to 600 pixels regardless of the screen size.break
tag for moving the next div to the following line.div
tag, we add our class, max-widthExample
. This class will add colors to div
along with the max-width property value, restricting this div
to not stretch over 600px.