css上下左右居中
如图:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上下左右居中</title> <style> html,body{ margin: 0; padding: 0; } .box { background: red; position:relative; width: 500px; height: 500px; top: 0; left: 0; margin: 0 auto; } .Center { background-color: yellow; /*上下居中*/ position: absolute; width: 200px; height: 200px; top: 50%; margin-top: -100px; /*height的一半 /*左右居中*/ left:0; right: 0; margin-left: auto; margin-right: auto; text-align: center; line-height:200px; } </style> </head> <div class="box"> <div class="Center" > 我是要居中的元素 </div> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>上下左右居中</title> <style type="text/css"> html,body{ margin: 0; padding: 0; } .box { position: relative; /*这个可以去掉 看看效果哦,注意会有变化啊*/ width: 600px; /*宽*/ height: 400px; /*高*/ background-color: rgba(212,66,33,.86); margin: 0 auto; } .Absolute-Center { width: 160px; height: 80px; background-color: green; position: absolute; top: 0; bottom: 0; left: 0; right: 0; /*css溢出法*/ margin: auto; } </style> </head> <body> <div class="box"> <div class="Absolute-Center" > 我是要居中的元素 </div> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>上下左右居中</title> <style type="text/css"> html, body { margin: 0; padding: 0; } .box { position: relative; width: 500px; height: 500px; background: red; margin: 0 auto; } .Center { width: 200px; height: 200px; background-color: yellow; position: relative; top: 50%; -moz-transform: translateY(-50%); -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); transform: translateY(-50%); margin: auto; text-align: center; line-height: 200px; } </style> </head> <body> <div class="box"> <div class="Center"> 我是要居中的元素 </div> </div> </body> </html>