ホームページ  >  記事  >  ウェブフロントエンド  >  DIV コンテンツを垂直方向に中央揃え_html/css_WEB-ITnose

DIV コンテンツを垂直方向に中央揃え_html/css_WEB-ITnose

WBOY
WBOYオリジナル
2016-06-24 11:22:301358ブラウズ

css の垂直方向のセンタリング属性設定vertical-align: middle は div では機能しません。例:

 1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 <head> 4 <meta charset="utf-8"> 5 <meta http-equiv="X-UA-Commpatible" content="IE=edge"> 6 <title>DIV垂直居中对齐</title> 7 <style type="text/css"> 8 * { 9     margin: 0;10     padding: 0;11 }12 13 html, body {14     width: 100%;15     height: 100%;16 }17 18 body {text-align: center; vertical-align: middle;}19 .outer {20     width: 400px;21     height: 120px;22     position: relative;23     left: 20px;24     top: 20px;25     text-align: center;26     vertical-align: middle;27     border: 1px dashed blue;28 }29 30 .button {31     width: 200px;32     height: 40px;33 }34 </style>35 </head>36 <body>37     <div class='outer'>38         <button class='button'>在DIV中垂直居中</button>39     </div>40 </body>41 </html>

実行後、ボタンが DIV 内で垂直方向の中央に配置されません:

解決策: div とボタン 高さは特定のピクセル値として決定されます。 ボタンの CSS 属性を直接設定できます。 位置: 相対; 上は (div.height - button.height)/2、左は (div.width) -button.height)/2; それ以外の場合は、ボタンと同じ幅と高さの div 親要素をボタンに追加し、位置を相対的に設定し、上と左を 50% に設定します (つまり、左上隅の位置が設定されます)。外側の div の中心に)、ボタンの左上隅の座標を設定します。これは、親要素 div の幅と高さの -50% です (ボタン自体の幅と高さとも同じです)。

詳細なコードは次のとおりです:

 1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 <head> 4 <meta charset="utf-8"> 5 <meta http-equiv="X-UA-Commpatible" content="IE=edge"> 6 <title>DIV垂直居中对齐</title> 7 <style type="text/css"> 8 * { 9     margin: 0;10     padding: 0;11 }12 13 html, body {14     width: 100%;15     height: 100%;16 }17 18 body {text-align: center; vertical-align: middle;}19 .outer {20     width: 400px;/* 或者为百分比 */21     height: 120px;22     position: relative;23     left: 20px;24     top: 20px;25     border: 1px dashed blue;26 }27 28 .inner {29     width: 200px;30     height: 40px;31     position: relative;32     position: relative;33     top: 50%;34     left: 50%;35 }36 37 .button {38     width: 200px;39     height: 40px;40     position: relative;41     top: -50%;42     left: -50%;43 }44 </style>45 </head>46 <body>47     <div class='outer'>48         <div class='inner'>49             <button class='button'>在DIV中垂直居中</button>50         </div>51     </div>52 </body>53 </html>

再度実行すると、div内のボタンが上下中央に表示されます

END

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。