Home >Web Front-end >CSS Tutorial >How to achieve vertical and horizontal centering with CSS
This article mainly introduces how to achieve vertical and horizontal centering in CSS, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
In the interview We are often asked how to use CSS to center an element vertically and horizontally. Especially when it comes to written test questions, this question appears more frequently. Of course, in our lives, there are often vertical Horizontal centering requirements.
In this case, it is easier, just set the container directly Text-align can achieve horizontal centering of content elements. To set vertical centering, you need to set the height of the container, and then set the easy line-height===height, as follows:
<p class="container"> <span>this is text</span> </p>
.container{ text-align: center; height: 50px; background: green; line-height: 50px; }
In this case, we use the position attribute combined with setting the offset to achieve this. First set the position of the container: relative, set the element position to absolute, and then set the offset of the element (.inner-box) top, left, margin-top, margin-left, where top and left are set to 50%, and margin The offset of -top/margin-left is half of the height/width of the element itself, which is a negative value.
The code is as follows:
<p class="container"> <p class="inner-box"></p> </p>
.container { height: 200px; width: 200px; background: pink; position: relative; } .inner-box { position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; height: 100px; width: 100px; background: green; }
This method is similar to method two, but the difference is that it cannot pass Set the margin-top/left offset to achieve the effect, because the width and height of the elements in the container are unknown. This time we set left/top/bottom/right:0, and then set margin:auto.
The code is as follows:
<p class="container"> <p class="inner-box"></p> </p>
.container { height: 200px; width: 200px; background: pink; position: relative; } .inner-box { position: absolute; height: 100px; width: 100px; top: 0; right: 0; left: 0; bottom: 0; margin: auto; background: green; }
There are many ways to achieve vertical and horizontal centering. It is also possible to set translate or use flex layout, but the methods written above It has better compatibility. If there are any deficiencies, please feel free to point them out.
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Use CSS to achieve various centering methods
The above is the detailed content of How to achieve vertical and horizontal centering with CSS. For more information, please follow other related articles on the PHP Chinese website!