Centering a Child Element

Centering a Child Element

Introduction

Centering an element is a usual task for a web developer. Images, modals, navigation anchor, and container of block of texts are the common components desired to be in the center. Semantically, Cascading Style Sheets (CSS) uses the word center to indicate that an element has equal spaces with respect to intended axis.

A programmer may center a content according to its x-axis (e.g. text-align: center), y-axis (e.g. vertical-align: middle), or both. This article explores common ways to put an element in the center and presents an unorthodox way for a special use case.

The Classical Way

The classical way to position an element in the center is through the use of margins of the child element. There are many variations for this technique. A developer in the past can conveniently use this technique in conjunction with the previous versions of CSS frameworks. Utilizing the 12-column grid system, a developer would the following steps below to determine the margin the child element would take.

  1. Resize the child element by an arbitrary number of columns. The number of columns should be an even number.
  2. Subtract the chosen number of columns from 12. The result is the number of unused columns that can be used as a margin.
  3. Divide the difference from step 2 because the unused space would distributed both horizontal sides of the child element.
  4. Depending on the CSS framework, the developer may offset the element by a certain number of column based on quotient in step 3. Otherwise, the quotient would be divided by 12 then multiplied to 100 to get the percentage of left margin.

Below is an example positioning the child element in the center using the classical technique programmed in vanilla CSS.

Example of child positioned in the horizontal center using margins.

The CSS code for the example above can be seen below. It uses calc() to derive the margin.

. classical .child {
width: calc(4 / 12 * 100%);
margin-left: calc(((12 - 4) / 2) / 12 * 100%)
}

Content of src/routes/articles/centering_a_child_element/+page.svelte instagingat KennethTrecy /kennethtrecy.pages.dev

Using Flexible Box Layout

Another method is through the use of flexible box layout which was introduced around 2012. It allows web developer to layout conveniently and responsively as the elements would automatically resize while adhering to the specified properties.

A web developer would declare certain properties on the parent like display: flex paired with flex-direction and/or flex-wrap. On the other hand, children of the flexible parent would have properties like flex-grow and/or flex-basis. It is very easy to make an element positioned in center in both axes using flexible box layout.

Below is an example positioning the child elements in the center (in both horizontal and vertical manner) using the flexible box layout programmed in vanilla CSS. Note that there is a margin between the two children to distinguish them.

Example of children positioned in the horizontal center and vertical center using flexible box layout.

Below is corresponding CSS code to center the children using flexible box layout.

. flexible .parent {
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
. flexible .child {
width: calc(1 / 3 * 100%);
margin: 0.1em;
}

Content of src/routes/articles/centering_a_child_element/+page.svelte instagingat KennethTrecy /kennethtrecy.pages.dev

Using Grid Layout

Next method is to use CSS Grid Layout. It is newest among other method layout mechanism. However, more than 96% users have browsers that can support it as of this writing, based from caniuse.com.

Below is an example positioning the child element in the center (in both horizontal and vertical manner) using the grid layout programmed in vanilla CSS.

Example of child positioned in the horizontal center and vertical center using grid layout.

Below is corresponding CSS code to center the child using grid box layout.

. grid-based .parent {
display: grid;
grid-template-rows: 1fr 1fr 1fr;
grid-template-columns: 1fr 1fr 1fr;
}
. grid-based .child {
grid-row-start: 2;
grid-row-end: 3;
grid-column-start: 2;
grid-column-end: 3;
}

Content of src/routes/articles/centering_a_child_element/+page.svelte instagingat KennethTrecy /kennethtrecy.pages.dev

The Unorthodox Way

The scenarios above are only applicable if the child element is smaller than its parent. However, there is a special case where in a child is bigger than its parent. As a demonstration, the special case can be seen in this website's home page. The home page requires the text container to 65 characters at most. However, there is a box that requires to be greater than its parent.

If the target box is limited to the full width of the parent in large screens, the text takes vertical space instead. See the image below.

Image of the hero content if it has the same exact width like its parent.

To increase the width of the target box, target box should use negative margins to balance.This gives an illusion that the target box is in the center of the parent despite that the child's width is bigger than parent's width. The following steps have been generalized to do the unorthodox way. Note that the instructions were based from comment in the source code of the home page.

  1. Let self be the target box.
  2. Let wo be the original width of self expressed in percentage. Therefore, it is 100%.
  3. Let wa be the width to be added to self expressed in percentage.
  4. Let wr be the resized width of self. The formula is wo + wa.
  5. Let ml be the left margin of resized self expressed in percentage. The left margin should be equal to -wa ÷ 2.

Below is a snapshot of home page using the unorthodox way. The wr is 125% and the ml is 12.5%.

Image of the hero content if it has the larger width than its parent.

To give another example, consider that a developer want to add another 60% of the current width. The solution can be seen below. The current width of self is 150 pixels.

  1. Let wo = 100%.
  2. Let wa = 60%.
  3. Let wr = wo + wa = 100% + 60% = 160%.
  4. Let ml = -wa ÷ 2 = -60% ÷ 2 = -30%.
  5. Expected width would be wr × 150 pixels = 240 pixels. On the other hand, the expected left margin would be ml × 150 pixels = -45 pixels.

Below is a live demonstration of the unorthodox way along with its CSS code.

Example of child positioned in the horizontal center only using negative left margin.

. unorthodox .child {
width: 140%;
margin-left: -20%;
}

Content of src/routes/articles/centering_a_child_element/+page.svelte instagingat KennethTrecy /kennethtrecy.pages.dev

Takeaways

Despite that there are different methods to position an element in the center, each has benefits and limitations. Centering based on 12-column layout may be rigid at the price of convenience. Using display: flex or display: grid, can center a child element as long as it is smaller than the parent yet not for bigger child. Meanwhile, using negative margins is only applicable bigger child element and not for smaller child element.

Usage of these techniques may depend on the programmer's style, requirements of the system being built, or supported browsers. There is no best solution at every scenario when it comes to centering child elements. There are also techniques not mentioned in this article such as using position property and others. It is left for the readers to study the other techniques.

References

Some portions in this article were based on third-party work(s) for educational purposes. They are copyright of the respective groups, organizations, companies, or persons that have been attributed below. Note that these works may have been shared under different licenses and may have notices (e.g. disclaimer of warranties) in the linked licenses. Should a work has no existing license(s), a link to the work have been still provided.

Disclaimer: Otherwise noted, the views or interests expressed in this site are my views, and does not necessarily reflect the view or interest of any entity I have a connection to; whether it is an organization, or someone I have worked with. In addition, trademarks (that may be mentioned in different pages) are the property of their respective owners and should not be interpreted as indicating endorsement, affiliation, or sponsorship, unless stated otherwise.

logo

Copyright © 2024 Kenneth Trecy Tobias.

Website's code(not texts such as containing my personal information) are under MIT license.

Socials

LinkedIn GitHub