Home >Web Front-end >HTML Tutorial >In HTML, center one element and right/left align other flexbox elements
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 content to remain the same, except that the rightmost one, i.e. T, moves to the right, like this −
P Q R S T
Now let's look at some examples to implement what we saw above.
The above layout can be achieved on a web page by using automatic margins and a new, invisible flex item −
<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>
In this example, we will use a pseudo-element with the same width as T. Use ::before to place it at the beginning of the container.
The Chinese translation ofLet’s look at an example now −
<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>
In this example, create a grid with multiple columns. Then position your items in the middle and end columns.
Let’s look at an example now −
<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>
The above is the detailed content of In HTML, center one element and right/left align other flexbox elements. For more information, please follow other related articles on the PHP Chinese website!