Positioning HTML Elements using CSS

Tyler Clark
InstructorTyler Clark
Share this video with your friends

Social Share Links

Send Tweet

Elements flow along the page depending on their display values, however we can customize them to be placed literally anywhere. We can position elements absolute or relative to a certain location, as well as fixed to the top of a page.

Instructor: [00:00] Inside of our HTML, I've added two divs here, with the class of parent and the inner div class of child. Let's give the parent class a padding of 20 pixels and a border of two pixels in blue. Now, we'll give the child a padding of 20 pixels and background of red. With that saved, we'll see it appear here at the top of the page.

[00:23] Now, back inside of our child class, let's give it a position of relative and a top of 20 pixels. We'll see with a refresh that our child box has now moved to the bottom of our parent class. We'll see that inside of our dev tools as well.

[00:38] The position property can help us manipulate the location of an element. When we use relative as the value, it's going to keep the element's original position in the flow of the document, which gives us the ability to use left, right, top, bottom, and z index.

[00:53] It's just going to nudge the element from its original position. Now, if we change this to absolute, we'll see that we can still move the element in any direction, but it's broken on the flow of the page. As we see, our parent div is smaller now, because it's not taking into effect the child's padding.

[01:13] Absolute positioning will change depending on which of its parent elements is positioned relative. Right now, it's positioned to the very top-level HTML element. As we add position relative to the parent class, we'll watch our red child box here move down. As it adjusts, it's 20 pixels from the top, but now, according to this parent class.

[01:34] Similar to absolute is the fixed value. However, fixed elements are always relative to the document, and not any parent element. Also, scrolling does not affect it, either. This is handy when working with navigations that stay at the top of a website.