Element centered layout

Horizontal and vertical centering

Horizontal centering method 1 (margin: 0 auto):

 

 

 Vertically centered method 1 (table-cell + vertical-align: middle):

 

 

(Hereinafter, since the theme displayed on the editor incomplete, so that only the code) 

Horizontal center Method 2 (absolute positioning):

<div style="width: 300px ; height:300px; background-color: red; position: relative">
  <div style="width: 100px;height:100px;background-color: yellow ;position: absolute; left:50%;margin-left: -50px"></div>
</div>

Similarly the corresponding vertically centered Method 2:

<div style="width: 300px ; height:300px; background-color: red; position: relative">
  <div style="width: 100px;height:100px;background-color: yellow ;position: absolute; top:50%;margin-top: -50px"></div>
</div>

Method horizontal center 3 (sub-div + floating relative positioning):

<div style="width: 300px ; height:300px; background-color: red ;">
  <div style="float:left;margin-left:50%; position:relative; left:-50px;width: 100px;height:100px;background-color: yellow ; "></div>
</div>

Similarly the corresponding vertically centered Method 3:

<div style="width: 300px ; height:300px; background-color: red ;">
  <div style="float:left;margin-top:50%; position:relative; top:-50px;width: 100px;height:100px;background-color: yellow ; "></div>
</div>

Method horizontal center 4 (flex):

<div style="display:flex; justify-content:center ;width: 300px ; height:300px; background-color: red ;">
  <div style="width: 100px;height:100px;background-color: yellow ; "> </div>
</div>

Similarly vertically centered Method 4:

<div style="display:flex; align-items:center;width: 300px ; height:300px; background-color: red ;">
  <div style="width: 100px;height:100px;background-color: yellow ; "> </div>
</div>

 

 

Guess you like

Origin www.cnblogs.com/btsn/p/11610436.html