LoginSignup
47
40

More than 5 years have passed since last update.

float で横並びさせてリストを中央揃え(センタリング)させる方法

Last updated at Posted at 2014-12-01

割りと簡単です。

html

<div class="hoge">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</div>

↑こんな感じのhtmlを想定します。

css

position: relative; を使います。

大枠の要素(別にdivでもpでも他でも大丈夫)から指定していきます。

.hoge {
  position: relative; 
  overflow: hidden; /* 下のulのcssでリスト全体を右に50%移動しているので、その分幅が広がってしまいスクロールバーが表示されてしまいます。それを防ぐ為の設定です。 */
}

.hoge ul {
  position: relative;
  left: 50%; /* リスト全体であるul要素を右に50%移動。つまり先頭を中央に持ってくる感じです。 */
  float: left;
}

.hoge ul li {
  position: relative;
  left: -50%; /* 各リスト項目になるli要素を左に50%移動。 */
  float: left;
  list-style: none; /* 項目にぼっちを出したくない場合はこれを設定(今回はあんまり関係ないですが) */
}

これで終わり。

References

47
40
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
40