How to Position and Align Elements Using CSS
Tags: html, css, beginners, webdev
Published: 2023-10-20 16:23:51

Starting from this article, we are going to begin talking about how to create webpage layouts, including how to position elements, how to align elements, how to create grids and flexboxes, as well as how to create responsive layouts that work on devices of all sizes.

First of all, let's start by discussing how to position and align elements using CSS.

> 📧 Subscribe to my newsletter: https://ericsdevblog.ck.page/profile

## How to position elements

[The `position` property](https://www.ericsdevblog.com/courses/html-css/4/#how-to-position-elements) controls how you wish to position an element. There are five different position methods available, including `static`, `relative`, `fixed`, `absolute`, and `sticky`. `static` is the default positioning method, meaning the element is not positioned in any special way. But things start to get more interesting, starting from the `relative` position.

### Relative position

With the relative positioning, the element will be placed relative to its default position. Its position can be adjusted by setting the `left`, `right`, `top`, or `bottom` properties.

```html
<p>. . .</p>
<p class="relative">. . .</p>
```

```css
p {
  border: 2px solid black;
}

p.relative {
  position: relative;
  left: 100px;
}
```

![position relative](https://www.ericsdevblog.com/courses/html-css/4/images/position-relative.gif)

### Fixed position

`fixed` position means that the element is positioned relative to the viewport. This method can be useful when you need to create a component, such as a navigation bar, that always stays at the top of the webpage, no matter the user's scrolling position. Or when you need to pop up window that stays at the bottom right corner.

```html
<p>. . .</p>
<p class="fixed">This element is fixed.</p>
```

```css
p {
  border: 2px solid black;
}

p.fixed {
  border: 2px solid orange;
  background-color: bisque;
  height: 100px;
  width: 100px;
  position: fixed;
  right: 0px;
  bottom: 0px;
}
```

![position fixed](https://www.ericsdevblog.com/courses/html-css/4/images/position-fixed.gif)

The `right` and `bottom` properties together anchor the `<div>` element to the bottom right corner of the webpage.

### Absolute position

If an element has the `absolute` position, it will be placed according to its closest positioned ancestor (has position method other than `static`).

```html
<div class="relative">
    This div has relative position
    <div class="absolute">This div has absolute position</div>
</div>
```

```css
div.relative {
  border: 2px solid black;
  width: 500px;
  height: 100px;
  position: relative;
  left: 10px;
}

div.absolute {
  border: 2px solid red;
  width: 250px;
  height: 50px;
  position: absolute;
  right: 10px;
  bottom: 0px;
}
```

![absolute position](https://www.ericsdevblog.com/courses/html-css/4/images/absolute-position.png)

In this example, `.relative` is a `500x100px` box with relative position, and `.absolute` is a smaller box placed inside `.relative`. As you can see, the `.absolute` box is positioned relative to the `.relative` box, instead of the viewport.

If the `absolute` element does not have a positioned ancestor, it will be positioned relative to the viewport, making it behave like a `fixed` element.

```css
div.relative {
  border: 2px solid black;
  width: 500px;
  height: 100px;
}

div.absolute {
  border: 2px solid red;
  width: 250px;
  height: 50px;
  position: absolute;
  right: 10px;
  bottom: 0px;
}
```

![absolute position without positioned ancestor](https://www.ericsdevblog.com/courses/html-css/4/images/absolute-no-ancester.png)

### Sticky position

The `sticky` option is similar to `fixed`, except that the element will only be fixed when a specific scroll threshold is reached. Like the left sidebar in [this page](https://www.ericsdevblog.com/courses/html-css/3/).

```html
<p>Lorem ipsum dolor sit amet . . .</p>
<p class="sticky">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatibus, sit!</p>
<p>. . .</p>
```

```css
p.sticky {
  border: 2px solid orange;
  background-color: bisque;
  position: sticky;
  top: 0px;
}
```

![position sticky](https://www.ericsdevblog.com/courses/html-css/4/images/position-sticky.gif)

## How to align elements

[Aligning elements](https://www.ericsdevblog.com/courses/html-css/4/#how-to-align-elements) is another important topic in web design. Making sure the elements are properly aligned allows you to create well-structured and visually pleasing webpages. Let's start by discussing how to center an element.

### Horizontally center an element

Recall that we discussed the box model in the previous chapter and learned about `margin`, which is space added outside the border. To horizontally center an element, you can simply set the left and right `margin` to `auto`.

```html
<div>
    <p>Lorem ipsum dolor . . .</p>
</div>
```

```css
div {
  border: 2px solid black;
  width: 500px;
  height: 300px;
}

p {
  border: 2px solid red;
  width: 250px;
  height: 150px;
  margin-left: auto;
  margin-right: auto;
}
```

![horizontally center element](https://www.ericsdevblog.com/courses/html-css/4/images/center-h.png)

In this example, we have two boxes with different sizes. By setting the horizontal margin of the smaller box to `auto`, your browser will automatically add equal space on both the left and right side of the paragraph element, hence centering the box horizontally.

### Vertically center an element with padding

When it comes to vertically centering elements, things get more complicated. The first solution is to add vertical padding to the bigger box `<div>`. Unfortunately, there isn't a simple `auto` option you can use here, and you'll have to do some calculations.

The bigger box is `300px` high, and the smaller box is `150px` high. The center of the smaller box is at `75px`. So if we push the box down `75px`, it should align with the center of the bigger box, which is at `150px`.

However, when you implement this solution, you will get a different result.

```css
div {
  border: 2px solid black;
  width: 500px;
  height: 300px;
  padding-top: 75px;
}

p {
  border: 2px solid red;
  width: 250px;
  height: 150px;
}
```

![vertically center element with padding](https://www.ericsdevblog.com/courses/html-css/4/images/center-v-padding.png)

The top space is smaller than the bottom space. That is because we haven't set [the `box-sizing` property](https://www.ericsdevblog.com/courses/html-css/3/#box-sizing) yet. By default, when the browser is calculating the height/width of an element, it only counts the content and does not include padding or the border width. For example:

```css
div {
  border: 10px solid black;
  padding: 20px 0;

  height: 100px;
}
```

This box has a `10px` thick border and `20px` vertical padding. And we define its height to be `100px`. But the actual height, as you can see, is `160px`.

![box sizing](https://www.ericsdevblog.com/courses/html-css/4/images/content-box.png)

The actual height, if you are counting border to border, equals two borders (`20px`), plus two paddings (`40px`), and plus the height of the content (`100px`), which is `160px`.

This can be very annoying as when we define the size of an element, we mean the box, from border to border, not just the content. Luckily, this can be changed using the `box-sizing` property we discussed in the previous chapter. It is set to `content-box` by default, and you need to change it to `border-box`.

```css
div {
  box-sizing: border-box;
  border: 10px solid black;
  padding: 20px 0;

  height: 100px;
}
```

![border box](https://www.ericsdevblog.com/courses/html-css/4/images/border-box.png)

Now, go back to our original problem. When trying to center an element using paddings, you must set `box-sizing: border-box;`, so that the browser counts the border width and paddings as part of the total height.

```css
* {
  box-sizing: border-box;
}

div {
  border: 2px solid black;
  width: 500px;
  height: 300px;
  padding-top: 75px;
}

p {
  border: 2px solid red;
  width: 250px;
  height: 150px;
}
```

Using the wildcard selector (`*`) makes sure that all boxes in the webpage have the same behavior.

![vertically center element](https://www.ericsdevblog.com/courses/html-css/4/images/center-v-box.png)

But wait, now we have another problem. The bottom space is now smaller than the top. This is because the `<p>` element comes with a default `16px` vertical margin. So you are actually pushing the element down `75px` + `16px` = `91px`. To fix that, you need to set the paragraph box's margin to 0.

```css
* {
  box-sizing: border-box;
}

div {
  border: 2px solid black;
  width: 500px;
  height: 300px;
  padding-top: 75px;
}

p {
  border: 2px solid red;
  width: 250px;
  height: 150px;
  margin: 0;
}
```

![margin removed](https://www.ericsdevblog.com/courses/html-css/4/images/center-v-margin.png)

Personally, I like to remove all default margins and paddings for all elements, so I would put this at the top of my CSS file:

```css
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
```

### Vertically center an element using position and transform

However, using paddings requires you to know the exact height of the boxes, but what if you don't have that information? For example, you are trying to display texts submitted by the user, and you don't know the length of that text. How can you vertically center it in this scenario?

```css
* {
  box-sizing: border-box;
}

div {
  border: 2px solid black;
  width: 500px;
  height: 300px;
}

p {
  border: 2px solid red;
  width: 300px;
  margin: 0;
}
```

![center text of arbitrary length](https://www.ericsdevblog.com/courses/html-css/4/images/center-text-arbitrary-length.png)

In this example, the paragraph only has the `width` set. Its height depends on the length of the text, which we do not know. In this case, we could utilize the combination of `position` and `transform` we just discussed.

```css
* {
  box-sizing: border-box;
}

div {
  border: 2px solid black;
  width: 500px;
  height: 300px;
  position: relative;
}

p {
  border: 2px solid red;
  width: 300px;
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
```

First of all, the `absolute` position, along with `top: 50%;` and `left: 50%;` will place the top left corner of the red box to the center point of the black box.

![absolute position, top 50% and left 50%](https://www.ericsdevblog.com/courses/html-css/4/images/abs-p-top-left.png)

And then `translate(-50%, -50%)` shifts the paragraph element's position back by 50% of its own width and height, aligning its center point with the black box's center point.

![center element with position and transform](https://www.ericsdevblog.com/courses/html-css/4/images/center-position-transform.png)

This technique ensures that the smaller box will always be centered inside the bigger box, even if the text is longer or shorter.

![center longer text](https://www.ericsdevblog.com/courses/html-css/4/images/center-longer.png)

Centering an element inside another element sounds like an easy task, but as you can see, it actually requires you to have a deep understanding of CSS.

### Left and right align elements

When it comes to aligning elements to the left or right, the most straightforward solution is, of course, the `absolute` position.

```html
<div class="container">
    <div class="div1">#1</div>
</div>
```

```css
.container {
  border: 2px solid black;
  width: 500px;
  height: 300px;
  position: relative;
}

.div1 {
  background-color: #e63946;
  position: absolute;
  right: 0px;
}
```

![absolute position right align](https://www.ericsdevblog.com/courses/html-css/4/images/absolute-right.png)

However, what if you have multiple `<div>` elements and want to put them in the same horizontal line but aligned to the left/right? You could micromanage each of them, but you would have to know the exact width of each element. A better solution is to use another property called `float`.

The following chart shows a common webpage layout with images and texts. The text flows around the image instead of letting the image take up the entire line, which wastes a lot of space.

![float](https://www.ericsdevblog.com/courses/html-css/4/images/float.excalidraw.png)

This effect is achieved with the `float` property. When an element is floated, it is taken out of the normal flow of the document, and other elements wrap around it based on the available space. For instance, you can make the image float to the left.

```html
<div class="container">
    <img src="images/image.jpg" alt="image">
    <p>Lorem ipsum dolor sit . . .</p>
</div>
```

```css
img {
  max-width: 200px;
  float: left;
}
```

![float left](https://www.ericsdevblog.com/courses/html-css/4/images/float-left.png)

Or you can also make the image float to the right.

```css
img {
  max-width: 200px;
  float: right;
}
```

![float right](https://www.ericsdevblog.com/courses/html-css/4/images/float-right.png)

Multiple elements can also float together.

```html
<div class="left">#1</div>
<div class="left">#2</div>
<div class="right">#3</div>
<p>. . .</p>
```

```css
div {
  padding: 20px 40px;
  border: 2px solid black;
}

.left {
  float: left;
}

.right {
  float: right;
}
```

![float multiple elements](https://www.ericsdevblog.com/courses/html-css/4/images/float-multiple.png)

## Conclusion

We discussed the fundamentals of positioning and aligning elements using CSS. While we covered many techniques, there is one commonly used approach that we didn't touch upon. But before we delve into it, we need to explore CSS grids and flexboxes. 📧 [Subscribe to my newsletter](https://ericsdevblog.ck.page/profile), and stay tuned for the next article!

If you are interested, here are some of my other articles about CSS and frontend design:

- [How to Create Transitions and Animations Using CSS](https://medium.com/gitconnected/how-to-create-transitions-and-animations-using-css-f5fff20dcaa2)
- [Working with Typography in CSS](https://medium.com/dev-genius/working-with-typography-in-css-ca700859fe27)
- [Three Ways of Defining Colors in CSS](https://medium.com/@huericnan/three-ways-of-defining-colors-in-css-7b2f98a3fbf3)
- [How to Position and Arrange Content Using CSS](https://www.ericsdevblog.com/courses/html-css/4/)
- [HTML & CSS: A Practical Guide](https://www.ericsdevblog.com/courses/html-css/)