9

div を水平方向に中央に配置したいのですが、css コードは次のとおりです。

<style type="text/css">
#footer{
    position: fixed;
    bottom: 20px;
    background-color: red;
    width:500px;
            margin: auto;/*left:auto; right:auto;*/
}
</style>

およびhtmlコード:

<body>
<div id="footer">hello world</div>
</body>

私のcssコードを説明する必要はないと思います.ほとんど自明ですが、divは水平方向に中央にありません.これを行う方法はありますか? 前もって感謝します。

4

4 に答える 4

21

これを試して

#footer{
    position: fixed;
    bottom: 20px;
    background-color: red;
    width:80%;
    margin: 0 0 0 -40%;
    left:50%;
}

JS フィドルの例

ここで注意すべき点は、体の 50% のmargin-leftちょうど半分の値の負の値をwidth設定することです。left

于 2013-04-17T11:32:36.807 に答える
8

これはうまくいくはずです。コンテナ div を追加することで機能します。

<style>

#footer-container{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
}

#footer
{
    width:500px;
    margin:0 auto;
    margin-bottom:20px;
    background-color:red;
}
</style>


<div id="footer-container">
      <div id="footer">hello world</div>
</div>
于 2013-04-17T11:37:59.403 に答える
6

その中に別の div を相対位置、margin: auto で配置します。固定幅を 100% にします。

それ以外の場合は、負のマージン「トリック」でハッキングできます

div { 
    position: fixed;
    left: 50%;
    width: 500px;
    margin-left: -250px;
}
于 2013-04-17T11:30:05.233 に答える
4

最新のブラウザーを使用している場合は、フレックスボックス レイアウト モジュールを使用できます: http://caniuse.com/#feat=flexbox

フレックスボックスのドキュメント: developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes
注: 私の担当者のため、2 つ以上のリンクを投稿することはできません。


JSFiddle

(簡単なので、footerタグの代わりにタグを使用します。)div#footer

<div id="footer-container">
  <footer>hello world</footer>
<div>
#footer-container {
  bottom: 20px;
  position: fixed;

  display: flex;
  justify-content: center;
  width: 100%;
}

footer {
  width: 500px;

  background-color: red;
}

justify-content: center;'centers'#footer-containerの子であり、この場合は単なるfooter要素です。

text-alignこれは、フッターのプロパティをリセットする必要がないことを除いて、Nick N. のソリューションと非常によく似ています。

その場合のフッターの幅は 500px ではなく可変 (80%) であるため、受け入れられた解決策はわずかにずれています。


親がform要素で、子がinput要素である場合flex: 1;input(子) 要素で使用し、max-width: 500px;代わりにを使用してwidth: 500px;ください。を使用flex: 1;するinputと、要素の幅を埋めるために要素が拡張されformますが、それ以外の場合はそうではありません。

于 2014-12-25T05:09:40.773 に答える