标签:了解 tom span 开始 png har copy 前端开发 身高
在前端开发过程中,盒子居中是常常用到的。其中 ,居中又可以分为水平居中和垂直居中。水平居中是比较容易的,直接设置元素的margin: 0 auto就可以实现。但是垂直居中相对来说是比较复杂一些的。下面我们一起来讨论一下实现垂直居中的方法。
首先,定义一个需要垂直居中的div元素,他的宽度和高度均为300px,背景色为橙色。代码如下:
<html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <style> .content { width: 300px; height: 300px; background: orange; } </style> </head> <body> <div class="content"></div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <style> .content { width: 300px; height: 300px; background: orange; margin: 0 auto; } </style> </head> <body> <div class="content"></div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <style> html, body { width: 100%; height: 100%; margin: 0; padding: 0; } .content { width: 300px; height: 300px; background: orange; margin: 0 auto; /*水平居中*/ } </style> </head> <body> <div class="content"></div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <style> html, body { width: 100%; height: 100%; margin: 0; padding: 0; } .content { width: 300px; height: 300px; background: orange; margin: 0 auto; /*水平居中*/ position: relative; /*设置position属性*/ } </style> </head> <body> <div class="content"></div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <style> html,body { width: 100%; height: 100%; margin: 0; padding: 0; } .content { width: 300px; height: 300px; background: orange; margin: 0 auto; /*水平居中*/ position: relative; /*脱离文档流*/ top: 50%; /*偏移*/ } </style> </head> <body> <div class="content"></div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <style> html,body { width: 100%; height: 100%; margin: 0; padding: 0; } .content { width: 300px; height: 300px; background: orange; margin: 0 auto; /*水平居中*/ position: relative; top: 50%; /*偏移*/ margin-top: -150px; } </style> </head> <body> <div class="content"></div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <style> html,body { width: 100%; height: 100%; margin: 0; padding: 0; } .content { width: 300px; height: 300px; background: orange; margin: 0 auto; /*水平居中*/ position: relative; top: 50%; /*偏移*/ transform: translateY(-50%); } </style> </head> <body> <div class="content"></div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <style> html,body { width: 100%; height: 100%; margin: 0; padding: 0; } body { display: flex; align-items: center; /*定义body的元素垂直居中*/ justify-content: center; /*定义body的里的元素水平居中*/ } .content { width: 300px; height: 300px; background: orange; } </style> </head> <body> <div class="content"></div> </body> </html>
标签:了解 tom span 开始 png har copy 前端开发 身高
原文地址:https://www.cnblogs.com/matd/p/13292172.html