Sizing
Sizing in CSS is in principle simple: set the height
and the width
of an element. Where it gets a little tricker is deciding what size unit to use to describe the dimensions.
This snippet will set the nav
element to the full viewport width (using the vw unit) and with a height of 5em.
nav {
width: 100vw;
height: 5em;
}
Sizing can depend on the display
property of an element. If the element has display: inline
, you can't set its size. This applies to SPAN
containers and links (A
), for example, which are inline by default. If you want to be able to set the size of an inline element, there are two strategies:
Option 1. Wrap it in an element which is a block or inline-block:
<style>
.links {
height: 2em;
width: 2em;
}
</style>
<div class="links">
<a href="#">My link</a>
</div>
With the DIV
wrapping (which is display: block
rather than display: inline
by default), we can now instead apply our desired sizing to the DIV
, and the A
will be affected by virtue of it being a child element.
This is most useful when you want to constrain the size of something - the child element won't by default expand to fill its parent.
Option 2. Change the display
property of the element:
<style>
.link {
display: inline-block;
height: 2em;
width: 2em;
}
</style>
<a href="#" class="link">My link</a>
Reference
- width, min-width, max-width (CSS Tricks)
- height, min-height, max-height (CSS Tricks)
Scrolling and overflow
If an element contains text or other elements too large for its size, it will overflow. You can control how an element overflows with the property overflow
, which can be set to visible
(the default), hidden
, scroll
or auto
.
Eg, to make our nav
element scroll:
nav {
width: 100vw;
height: 5em;
overflow: scroll;
}
You can also adjust the overflow on a horizontal (x) or vertical (y) basis using the properties overflow-x
and overflow-y
.
Reference
- overflow (CSS Tricks)
Margins and Padding
The margin
and padding
properties affect the internal sizing of an element. There are a few ways to set them.
You can set each margin/padding on its own:
.intro {
margin-left: 1rem;
margin-bottom: 1.1rem;
}
Or set them together, by listing the top, right, bottom, left margin/padding in order:
.intro {
margin: 0 0 1.1rem 1rem;
padding: 1rem 1rem 1rem 1rem;
}
Use 0
for margins you want to remove, or auto
to let the browser figure it out. If you want to set all the margins/paddings to be the same, you can just use: margin: 1rem
, for example.
Reference
Size doesn't fit contents
If a parent element has child elements which float, its computed size might be too small, and not visibly contain the child elements. This is especially obvious if you use a background or border for your parent element.
Adding a dummy DIV
with a 'clearfix' just before you close the parent element, you can fix it:
<div>
<div>floated...</div>
<div style="clear:both;"></div>
</div>
Read more
- The 'Clearfix' (CSS Tricks)
- Contains don't clear floats (CSS Tricks)