Sitemap / Advertise

Information



Tags



Share

How to align elements vertically using :root selector in CSS

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

In this tutorial, I will show you how to align elements using the :root selector and the var() function in plain CSS without using a preprocessor scripting language like SASS.

It might be most-searched-question among CSS novices to align an HTML element vertically in CSS without implementing JavaScript. As it follows, I wanted to show you a simple way to manage that without being struggled by preprocessors or JS functions.

Syntax:

:root

The :root CSS pseudo-class matches the root element of a tree representing the document. In HTML, :root represents the <html> element and is identical to the selector html, except that its specificity is higher(1).

var()

The var() CSS function can be used to insert the value of a custom property (sometimes called a "CSS variable") instead of any part of a value of another property. The var() function cannot be used in property names, selectors or anything else besides property values(2).

calc()

The calc() function takes a single expression as its parameter, with the expression's result used as the value. The expression can be any simple expression combining the following operators, using standard operator precedence rules(3).

Code

Define the size variables of the parent and the child element - height and width - in the :root selector.

Use the var() function to elicit the pre-defined size variables that of the parent element.

In the calc() function, calculate the vertical position of the child element (top) using the parent height and the child height to align the child element vertically depending on the height of the parent element.

For each element, set margin as auto to align them horizontally.


------------------- CSS --------------------

:root{
	--parent-height: 300px;
	--parent-width: 300px;
	--child-height: 200px;
	--child-width: 200px;
}

.parent{
	background-color: yellow;
	width: var(--parent-width);
	height: var(--parent-height);
	margin: auto;
	
}

.child{
	background-color: green;
	width: var(--child-width);
	height: var(--child-height);
	position:relative;
	top: calc(var(--parent-height) / 2 - var(--child-height) / 2);
	margin: auto;
}

------------------- HTML --------------------

<div class="parent">
<div class="child">
</div>
</div>

Result:

References

(1) https://developer.mozilla.org/en-US/docs/Web/CSS/:root

(2) https://developer.mozilla.org/en-US/docs/Web/CSS/var

(3) https://developer.mozilla.org/en-US/docs/Web/CSS/calc