方法 1: 使用 position+transform
主要使用了 CSS3 中 transform 进行元素偏移, 效果非常好
这方法功能很强大, 也比较灵活, 不仅仅局限在实现居中显示. 兼容方面也一样拿 IE 来做比较, 第二种方法 IE8 以上都能使用. IE8 及 IE8 以下都会出现问题.
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="utf-8">
- <style>
- body, HTML { margin: 0; width: 100%; height: 100%; } #box { width: 100%;
- height: 100%; background: rgba(0, 0, 0, 0.7); position: relative; } #content
- { position: absolute; background: pink; left: 50%; transform: translateX(-50%);
- -webkit-transform: translateX(-50%); }
- </style>
- </head>
- <body>
- <body>
- <div id="box">
- <div id="content">
- div 被其中的内容撑起宽高
- </div>
- </div>
- </body>
- </body>
- </HTML>
方法 2: 利用 flex 进行布局
- <!DOCTYPE HTML>
- <HTML>
- <head>
- <meta charset="utf-8">
- <style>
- body, HTML { margin: 0; width: 100%; height: 100%; } #box { width: 100%;
- height: 100%; background: rgba(0, 0, 0, 0.7); display: flex; justify-content:
- center; align-items: center; } #content { width: 50%; height: 50%; background:
- pink; }
- </style>
- </head>
- <body>
- <body>
- <div id="box">
- <div id="content">
- div 被其中的内容撑起宽高
- </div>
- </div>
- </body>
- </body>
- </HTML>
方法 3: 兼容性最好的方案 (不能算严格意义上的不定宽高, 子 div 不能根据内容大小做改变):
第一种方法出现的比较早. 兼容拿 IE 来做参照 --> 第一种方法 IE7 以上都能使用, IE7 及 IE7 以下都会出现问题.
- <body>
- <div id="box">
- <div id="content"></div>
- </div>
- </body>
- body,
- HTML {
- margin: 0;
- width: 100%;
- height: 100%;
- }
- #box {
- width: 100%;
- height: 100%;
- background: rgba(0, 0, 0, 0.7);
- position: relative;
- }
- #content {
- width: 50%;
- height: 50%;
- background: pink;
- position: absolute;
- top: 0;
- right: 0;
- bottom: 0;
- left: 0;
- margin: auto;
- }
原理不是很明白, 但是这种方式并不完善, content 只能设置固定宽高, 无甚意义.
更多前端开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/css3/16012.html