0

javascriptなしで絶対/相対的に配置された要素を中央に配置する方法は本当にありませんか? 要素の幅が信頼できるものであれば簡単です。CSS ソリューションはありませんか? JavaScript に頼らざるを得ないのですか?

<body><div class="parent"><div class="child">This stuff changes</div></div></body>

.child{margin:auto;position:absolute;left:50%} // this will center the left edge
.parent{width:800px;height:430px;margin:auto;overflow:hidden;}
4

1 に答える 1

4

どうですか:

.child {
    margin-left: auto;
    margin-right: auto;
    display: table;
}

完全なデモ HTML:

<html>
<head>
    <style type="text/css" media="screen">
    .child {
        margin-left: auto;
        margin-right: auto;
        display: table;
    }
    </style>
</head>
<body>
    <!-- middle marker to test alignment -->
    <table width="100%"><tr><td align="center" width="100%">|</td></tr></table>
    <!-- actual thing we're trying to center -->
    <div class="parent">
        <div class="child">123456789|987654321</div>
    </div>
</body>

(ソース: http://solstice.co.il/blog/2008-02-26/horizo​​ntally-centering-content-dynamic-width-css )

垂直センタリングの場合:

<html>
<head>
    <style type="text/css" media="screen">
    .parent {
        width:800px;
        height:430px;
        margin:auto;
        overflow:hidden;
        border:2px solid cyan;
        border-radius:25px;
        -moz-border-radius:25px; /* Firefox 3.6 and earlier */
    }
    .evilStepMother { /* i.e. comes between the parent and child */
        display: table-cell;
        vertical-align: middle;
        width: 800px; /* i.e. matches parent */
        height: 430px; /* i.e. matches parent */
        border:2px solid green;
        border-radius:25px;
        -moz-border-radius:25px; /* Firefox 3.6 and earlier */
    }
    .child {
        margin: auto;
        display: table;
        border:2px solid red;
        border-radius:25px;
        -moz-border-radius:25px; /* Firefox 3.6 and earlier */
    }
    </style>
</head>
<body>
    <!-- middle marker to test alignment -->
    <table width="100%"><tr><td align="center" width="100%">|</td></tr></table>
    <!-- actual thing we're trying to center -->
    <div class="parent"><div class="evilStepMother">
        <div class="child">123456789|987654321</div>
    </div></div>
</body>

注: 境界線は、物事がどのように配置されているかを簡単に確認できるようにするためのものです。曲がりくねった角はちょうどいいです。

(ソース: http://blog.themeforest.net/tutorials/vertical-centering-with-css/ )

于 2012-10-18T20:32:52.230 に答える