1、水平居中:
(1) 行内元素
设置父元素:
text-align:center
- <head>
- <style type="text/CSS">
- #out{ width:200px; height:100px; background-color:red; text-align:center;
- }
- </style>
- </head>
- <body>
- <div id="out">
- <span>
- CSS
- </span>
- </div>
- </body>
(2) 非行内元素
a、设置子元素:
width
margin:auto
- <head>
- <style type="text/css">
- #out{ width:200px; height:100px; background-color:red; } #in{ width:50px;
- height:25px; background-color:yellow; margin-left:auto; margin-right:auto;
- }
- </style>
- </head>
- <body>
- <div id="out">
- <div id="in">
- </div>
- </div>
- </body>
b、设置父元素和子元素
设置父元素:
text-align:center
设置子元素:
display:inline-block
- <head>
- <style type="text/css">
- #out{ width:200px; height:100px; background-color:red; text-align:center;
- } #in{ width:50px; height:25px; background-color:yellow; display:inline-block;
- }
- </style>
- </head>
- <body>
- <div id="out">
- <div id="in">
- </div>
- </div>
- </body>
2、垂直居中
(1) 行内元素
设置子元素:
line-height: 父元素 height
- <head>
- <style type="text/css">
- #out{ width:200px; height:100px; background-color:red; } span{ line-height:100px;
- } }
- </style>
- </head>
- <body>
- <div id="out">
- <span>
- CSS
- </span>
- </div>
- </body>
(2) 非行内元素
设置父元素:
position:relative
设置子元素:
position:absolute
margin-top:(父元素 height - 子元素 height)/2
- <head>
- <style type="text/css">
- #out{ position: relative; width: 200px; height: 100px; background: red;
- } #in{ position: absolute; width: 100px; height: 50px; background: yellow;
- margin-top: 25px; }
- </style>
- </head>
- <body>
- <div id="out">
- <div id="in">
- </div>
- </div>
- </body>
3、水平和垂直居中
(1) 在浏览器窗口中水平和垂直居中
设置:
position:fixed
left:50%
top:50%
margin-top:-height/2
margin-left:-width/2
- <head>
- <style type="text/css">
- #out{ position: fixed; width: 800px; height: 400px; background: red; margin:
- -200px 0 0 -400px; left: 50%; top:50%; } }
- </style>
- </head>
- <body>
- <div id="out">
- </div>
- </body>
(2) 子元素在父元素中水平和垂直居中
父元素:
position:fixed
子元素:
position:absolute
left:50%
top:50%
margin-left:-(width+2*padding)/2
margin-top:-(height+2*padding)/2
- <head>
- <style type="text/css">
- #out{ position: fixed; width: 400px; height: 200px; background: red; }
- #in{ width: 100px; height: 50px; background: yellow; padding: 20px; position:
- absolute; top: 50%; left: 50%; margin-left: -70px; /* (width + padding)/2
- */ margin-top: -45px; /* (height + padding)/2 */ }
- </style>
- </head>
- <body>
- <div id="out">
- <div id="in">
- </div>
- </div>
- </body>
就爱阅读 www.92to.com 网友整理上传, 为您提供最全的知识大全, 期待您的分享,转载请注明出处。
来源: http://www.92to.com/bangong/2016/12-12/14280151.html