Center one and right/left align other flexbox element in HTML


Let’s say we have P, Q,R,S,T aligned in the center of a web page −

                                P Q R S T 

We want the above to remain same, except the rightmost i.e. the T to shift on the right, like this −

                                 P Q R S                                 T 

Let us now see some examples to achieve what we saw above.

Center one and right/ left align other flexbox element with auto margins

Example

With a combination of auto margins and a new, invisible flex item the above layout can be achieved on a web page −

<html> <title>Example</title> <head> <style> li:first-child { margin-right: auto; visibility: hidden; } li:last-child { margin-left: auto; background: orange; } ul { padding: 0; margin: 0; display: flex; flex-direction: row; justify-content: center; align-items: center; } li { display: flex; margin: 3px; padding: 10px; background: red; } p { text-align: center; margin-top: 0; } </style> <head> <body> <ul> <li>T</li> <li>P</li> <li>Q</li> <li>R</li> <li>S</li> <li>T</li> </ul> </body> <html>

Center one and right/ left align other flexbox element with pseudo element

In this example, we will create a pseudo-element with the same width as T. Place it at the start of the container with ::before.

Example

Let us now see the example −

<html> <title>Example</title> <head> <style> ul::before { content: "T"; margin: 1px auto 1px 1px; visibility: hidden; padding: 5px; background: orange; } li:last-child { margin-left: auto; background: orange; } ul { padding: 0; margin: 0; display: flex; flex-direction: row; justify-content: center; align-items: center; } li { display: flex; margin: 3px; padding: 10px; background: red; } </style> <head> <body> <ul> <li>P</li> <li>Q</li> <li>R</li> <li>S</li> <li>T</li> </ul> </body> <html>

Center one and right/ left align other flexbox element with Grid Layout

In this example, create a grid with multiple columns. Then position your items in the middle and end columns.

Example

Let us now see the example −

<html> <title>Example</title> <head> <style> ul { display: grid; grid-template-columns: 1fr repeat(4, auto) 1fr; grid-column-gap: 5px; justify-items: center; } li:nth-child(1) { grid-column-start: 2; } li:nth-child(5) { margin-left: auto; } ul { padding: 0; margin: 0; list-style: none; } li { padding: 10px; background: red; } p { text-align: center; } </style> <head> <body> <ul> <li>P</li> <li>Q</li> <li>R</li> <li>S</li> <li>T</li> </ul> </body> <html>

Advertisements