關于如何在div中居中一個元素,應該是一個前段開發(fā)者在前前期常遇到的問題,下面我總結了一下我知道的和大家分享,當然,如果寫的不對,還請大家留言指點。
居中一般都是在塊元素中居中的
1.元素中 只有文本或者元素是內聯(lián)元素
<style type="text/css"> div{ width:600px; height: 100px; background-color: #444444; display: table-cell; /*表格樣式 display: table-cell;*/ vertical-align: middle; /*使當前元素內的內容上下居中 vertical-align: middle;*/ text-align: center; /*文本居中*/ /*這三句代碼可使當前元素內的文本上下左右居中*/ } </style> <div> 元素 </div>
點擊 "運行實例" 按鈕查看在線實例
也可以給元素添加一個p標簽
2.里面包裹著一個塊元素
<style type="text/css"> .box{ width:600px; height: 100px; background-color: #444444; display: table-cell; /*表格樣式 display: table-cell;*/ vertical-align: middle; /*使當前元素內的內容上下居中 vertical-align: middle;*/ } .box1{ width: 20px; height: 30px; margin: auto; background-color: #ccc; } </style> </head> <body> <div class="box"> <div class="box1"></div> </div> </body>
點擊 "運行實例" 按鈕查看在線實例
3. 這兩句比第一種更方便點,效果和第一個一樣 // 固定高的情況下使用這種方法
text-align: center;
line-height: 100px;
<style type="text/css"> div{ width:600px; height: 100px; background-color: #444444; color:#fff; text-align: center; line-height: 100px; /*文本上下左右居中*/ } </style> <div> 131321 </div>
點擊 "運行實例" 按鈕查看在線實例
4.這一種就比較抽象了。利用的是position定位,
relative 相對定位 相對與當前文檔流
<style type="text/css"> div{ width:600px; height: 100px; background-color: #444444; } p{ width: 50px; height: 50px; position: relative; top:50%; left: 50%; margin-top:-25px; margin-left:-25px; color: #fff; } </style> <div> <p>123</p> </div>
點擊 "運行實例" 按鈕查看在線實例
absolute 絕對定位 當沒有父元素relative時 相對與整個HTML定位
fixed 固定定位
這兩個大家就自己試試,畢竟紙上得來終覺淺
插播一列 常用的居中方法
看代碼
<style type="text/css"> div{ min-width:300px; height: 100px; background-color: #444444; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; } </style> <div> </div>
點擊 "運行實例" 按鈕查看在線實例
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號