This refers to the horizontal center of course is to say through the CSS to automatically control, and not to say after the calculation, set a position to refer to the settlement.
In general, there are three ways to achieve this:
In the implementation, we define two nouns to facilitate the following explanation: out--contains the container that needs to be centered, in--the element that needs to be centered.
1. Text-align:center
- Set the text-align:center of the Out
- Ensure that the in display is inline
2. Margin-left:auto; Margin-right:auto
- Set the Margin-left:auto of in; Margin-right:auto
- Guaranteed in Display as Block
3. Negative margin mode
- Set the Position:absolute of in
- Set the left:50% of in
- Set in Margin-left: Half of the width of the negative in (for example in the width is 100px, then set here for -50px)
- Set the position:absolute/relative of the Out
- Need to know clearly the width of in
Three ways to use it is relatively simple, but all have their own scope of application, the above given is to reach the center of the target and the need for the conditions, where the red Spot is the condition, but also the limitations of the method.
The first two principles are relatively good understanding, the third principle of a little talk about, but also very good understanding:
Essentially two steps, the first in moving through the left:50% to the middle of the out, if in is just a line, then here actually the work is done. But if the in has a width, then it will be found that the border is located just in the middle of the out. Ok
Obviously, the second step is to move in and to the left half of the in width so that the middle of in is in the middle of the out, that is, in the middle of the out.
Below with in and out are all div to give the code, the code contains all three ways can also directly click on the following demo address http://demo.zhengjiachao.com/css/hori-center.html
<!DOCTYPE HTML><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /><Scripttype= "Text/javascript"src=".. /resource/js/jquery-1.7.2.js "></Script><styletype= "Text/css">. out{Height:200px;Background-color:Orange;margin:10px;}. in{width:100px;Height:100px;Background-color:Gray;}. Out.type-1{text-align:Center;}. In.type-1{Display:inline;}. In.type-2{margin:0 Auto;}. out.type-3{position:relative;}. in.type-3{position:Absolute; Left:50%;Margin-left:-50px;}</style></Head><Body><Divclass= "Out type-1"> <Divclass= "in Type-1">1 Text-align:center</Div></Div><Divclass= "Out type-2"> <Divclass= "in Type-2">2 margin:0 Auto; </Div></Div><Divclass= "Out type-3"> <Divclass= "in Type-3">3 Negative margin</Div></Div><Scripttype= "Text/javascript"></Script></Body></HTML>