HTML Skills: several ways to achieve horizontal and vertical elements centered

How to use html + css to achieve horizontal and vertical centering effect element, which is the question we will be making page coding frequently used.

1) Center line of text

The main realization css code:

Center Horizontally: text-align: center; vertical center: line-height: XXpx; / * matches the value of the height of the line-height of the element * /

Let's look at an example of this, join us here have a div, width and height of 300px, the background color is black, and then there is the div in a short line of text, we only need to use line-height: 200px; text can be achieved centering effect, the specific code as follows:

From the above chart we can see that we achieve vertical centering effect single line of text, the text but many times we do not know the exact number, there may be a line, there may be many rows, then we have a multi-line text of this problem we how to deal with it.

2) the vertical center lines of text

For multiple lines of text vertically centered We realize there are many ways that we look at here one by one;

1, using display: table to achieve

Mainly realize code:

display: table making a block-level element becomes massive form;

display: table-cell; sub-element arranged table cells;

vertical-align: middle; so that center the table content can achieve the effect of the vertical center;

Html css and the specific code as follows:

2, using absolute and transform with the realization

Mainly realize code:

position: absolute; first of all to the absolute positioning of text;

left: 50%; top: 50%; transform: translate (-50%, - 50%); let the text box on the left and from the top 50%, respectively, and then transform to the left (on) translating its own width (height) 50% also reached a centering effect.

Html css and the specific code as follows:

3, the use of flex achieve

Mainly realize code:

display: flex; setting a display attribute value which is defined as flex elastic container

align-items: center;定义项目在交叉轴(纵轴)上如何对齐,垂直对齐居中

justify-content: center; 定义了项目在主轴上的对齐方式,水平对齐居中

具体的html与css的代码就如下所示:

好了,本篇文章就给大家说到这里,大家自己动手写一下看能不能写出一样的页面效果出来,也可以找一些类似的页面自己练习一下。

转载自:https://baijiahao.baidu.com/s?id=1622460301039180175&wfr=spider&for=pc

Guess you like

Origin www.cnblogs.com/zmdComeOn/p/11088817.html