5

HTML(垂直および水平)でのdivの中央揃えに問題があります。私のコードは次のようになります。

<div id="container">SOME HTML</div>

#container{
    width: 366px;
    height: 274px;
    margin: 50%;
    top: -137px;
    left: -188px;
    position:absolute;
}

このdivを画面の中央にクロームセンターで配置するだけです。

4

6 に答える 6

7

<div>これにより、水平方向の中央に配置されます。

#container{
    width: 366px;
    height: 274px;
    margin: 0 auto;
}

垂直方向の中央揃えは非常に単純ではありません。そのためにjavascriptを使用する必要があるか、このcssソリューションを試してください。

于 2012-04-24T15:41:04.617 に答える
2
#container{
    width: 366px;
    height: 274px;
    top: 50%;
    left: 50%;
    margin: -137px 0 0 -188px;
    position:absolute;
}
于 2012-04-24T15:42:34.587 に答える
1

あなたが使用することができます:

#container {
    // Your other values, but remove position: absolute;
    margin: 0 auto;
}

または、次のことを行うことができます。

#wrapper, #container {
    border: 1px solid red;
    height: 500px;
    width: 600px;
}

#wrapper {
    bottom: 50%;
    right: 50%;
    position: absolute;
}

#container {
    background: yellow;
    left: 50%;
    padding: 10px;
    position: relative;
    top: 50%;
}

そして、あなたはHTMLコードです:

<div id="wrapper">
    <div id="container">
        <h1>Centered Div</h1>
        <p>
            This div has been centered within your browser window.</p>
    </div>
</div>

これ<div>により、はブラウザウィンドウの中央に配置されます。

于 2012-04-24T15:41:22.417 に答える
1

これはトリックを行います(垂直および水平):

#container{
    position: absolute;
    width: 366px;
    height: 274px;
    left: 50%;
    top: 50%;
    margin-left: -183px; /* half width */
    margin-top: -137px; /* half height */
}
于 2012-04-24T15:42:52.383 に答える
1

これを試してください:

<div class="cont">
  <div class="box"></div>
</div>

Css:

.cont{
  background-color: tomato;
  width: 600px;
  height: 400px;
  position: relative;
}
.box {
  width:100px;
  height:100px;
  background-color: teal;
  color:#fff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%)
}
于 2015-03-19T12:40:11.153 に答える
-1

CSSだけを使用しても問題ありません。

これがデモです

#container{
    width: 366px;
    height: 274px;
    margin: 50%;
    top: 50%;
    left: 50%;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
}​
于 2012-04-24T15:42:10.590 に答える