Как горизонтально выровнять ul по центру div?

Я пытаюсь центрировать <ul> внутри <div>. Я попробовал следующее

text-align: center;

и

left: 50%;

Это не работает.

CSS:

.container { 
    clear: both; 
    width: 800px; 
    height: 70px; 
    margin-bottom: 10px;
    text-align: center;
}

.container ul { 
    padding: 0 0 0 20px; 
    margin: 0; 
    list-style: none;
}

.container ul li { 
    margin: 0; 
    padding: 0; 
}

Я хочу, чтобы ul располагалось по центру внутри контейнера.


person Si8    schedule 05.06.2013    source источник


Ответы (4)


Ниже приведен список решений для центрирования объектов в CSS по горизонтали. Фрагмент включает в себя все из них.

html {
  font: 1.25em/1.5 Georgia, Times, serif;
}

pre {
  color: #fff;
  background-color: #333;
  padding: 10px;
}

blockquote {
  max-width: 400px;
  background-color: #e0f0d1;
}

blockquote > p {
  font-style: italic;
}

blockquote > p:first-of-type::before {
  content: open-quote;
}

blockquote > p:last-of-type::after {
  content: close-quote;
}

blockquote > footer::before {
  content: "\2014";
}

.container,
blockquote {
  position: relative;
  padding: 20px;
}

.container {
  background-color: tomato;
}

.container::after,
blockquote::after {
  position: absolute;
  right: 0;
  bottom: 0;
  padding: 2px 10px;
  border: 1px dotted #000;
  background-color: #fff;
}

.container::after {
  content: ".container-" attr(data-num);
  z-index: 1;
}

blockquote::after {
  content: ".quote-" attr(data-num);
  z-index: 2;
}

.container-4 {
  margin-bottom: 200px;
}

/**
 * Solution 1
 */
.quote-1 {
  max-width: 400px;
  margin-right: auto;
  margin-left: auto;
}

/**
 * Solution 2
 */
.container-2 {
  text-align: center;
}

.quote-2 {
  display: inline-block;
  text-align: left;
}

/**
 * Solution 3
 */
.quote-3 {
  display: table;
  margin-right: auto;
  margin-left: auto;
}

/**
 * Solution 4
 */
.container-4 {
  position: relative;
}

.quote-4 {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

/**
 * Solution 5
 */
.container-5 {
  display: flex;
  justify-content: center;
}
<main>
  <h1>CSS: Horizontal Centering</h1>

  <h2>Uncentered Example</h2>
  <p>This is the scenario: We have a container with an element inside of it that we want to center. I just added a little padding and background colors so both elements are distinquishable.</p>

  <div class="container  container-0" data-num="0">
    <blockquote class="quote-0" data-num="0">
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>
      <footer>Tasha Yar about Data</footer>
    </blockquote>
  </div>

  <h2>Solution 1: Using <code>max-width</code> & <code>margin</code> (IE7)</h2>

  <p>This method is widely used. The upside here is that only the element which one wants to center needs rules.</p>

<pre><code>.quote-1 {
  max-width: 400px;
  margin-right: auto;
  margin-left: auto;
}</code></pre>

  <div class="container  container-1" data-num="1">
    <blockquote class="quote  quote-1" data-num="1">
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>
      <footer>Tasha Yar about Data</footer>
    </blockquote>
  </div>

  <h2>Solution 2: Using <code>display: inline-block</code> and <code>text-align</code> (IE8)</h2>

  <p>This method utilizes that <code>inline-block</code> elements are treated as text and as such they are affected by the <code>text-align</code> property. This does not rely on a fixed width which is an upside. This is helpful for when you don’t know the number of elements in a container for example.</p>

<pre><code>.container-2 {
  text-align: center;
}

.quote-2 {
  display: inline-block;
  text-align: left;
}</code></pre>

  <div class="container  container-2" data-num="2">
    <blockquote class="quote  quote-2" data-num="2">
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>
      <footer>Tasha Yar about Data</footer>
    </blockquote>
  </div>

  <h2>Solution 3: Using <code>display: table</code> and <code>margin</code> (IE8)</h2>

  <p>Very similar to the second solution but only requires to apply rules on the element that is to be centered.</p>

<pre><code>.quote-3 {
  display: table;
  margin-right: auto;
  margin-left: auto;
}</code></pre>

  <div class="container  container-3" data-num="3">
    <blockquote class="quote  quote-3" data-num="3">
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>
      <footer>Tasha Yar about Data</footer>
    </blockquote>
  </div>

  <h2>Solution 4: Using <code>translate()</code> and <code>position</code> (IE9)</h2>

  <p>Don’t use as a general approach for horizontal centering elements. The downside here is that the centered element will be removed from the document flow. Notice the container shrinking to zero height with only the padding keeping it visible. This is what <i>removing an element from the document flow</i> means.</p>

  <p>There are however applications for this technique. For example, it works for <b>vertically</b> centering by using <code>top</code> or <code>bottom</code> together with <code>translateY()</code>.</p>

<pre><code>.container-4 {
    position: relative;
}

.quote-4 {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}</code></pre>

  <div class="container  container-4" data-num="4">
    <blockquote class="quote  quote-4" data-num="4">
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>
      <footer>Tasha Yar about Data</footer>
    </blockquote>
  </div>

  <h2>Solution 5: Using Flexible Box Layout Module (IE10+ with vendor prefix)</h2>

  <p></p>

<pre><code>.container-5 {
  display: flex;
  justify-content: center;
}</code></pre>

  <div class="container  container-5" data-num="5">
    <blockquote class="quote  quote-5" data-num="5">
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>
      <footer>Tasha Yar about Data</footer>
    </blockquote>
  </div>
</main>


display: flex

.container {
  display: flex;
  justify-content: center;
}

Примечания:


max-width и margin

Вы можете центрировать элемент уровня блока по горизонтали, назначив фиксированную ширину и установив margin-right и margin-left на auto.

.container ul {
  /* for IE below version 7 use `width` instead of `max-width` */
  max-width: 800px;
  margin-right: auto;
  margin-left: auto;
}

Примечания:

  • Контейнер не нужен ????
  • Требуется, чтобы была известна (максимальная) ширина центрированного элемента ????

IE9+: transform: translatex(-50%) и left: 50%

Это похоже на причудливый метод центрирования, который использует абсолютное позиционирование и отрицательные поля.

.container {
  position: relative;
}

.container ul {
  position: absolute;
  left: 50%;
  transform: translatex(-50%);
}

Примечания:

  • Центральный элемент будет удален из потока документов. Все элементы будут полностью игнорировать центрированный элемент. ????????????
  • Этот метод позволяет вертикально центрировать, используя top вместо left и translateY() вместо translateX(). Их можно даже совмещать. ????
  • Поддержка браузера: transform2d

IE8+: display: table и margin

Как и в первом решении, вы используете автоматические значения для правого и левого полей, но не назначаете ширину. Если вам не нужна поддержка IE7 и ниже, это лучше подходит, хотя использование значения свойства table для display кажется несколько хакерским.

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

IE8+: display: inline-block и text-align

Также возможно центрирование элемента, как если бы вы делали это с обычным текстом. Недостаток: вам нужно присвоить значения как контейнеру, так и самому элементу.

.container {
  text-align: center;
}

.container ul {
  display: inline-block;

  /* One most likely needs to realign flow content */
  text-align: initial;
}

Примечания:

  • Не требует указания (максимальной) ширины ????
  • Выравнивает содержимое потока по центру (потенциально нежелательный побочный эффект) ????
  • Хорошо работает с динамическим количеством элементов меню (например, в случаях, когда вы не можете знать ширину, которую займет один элемент) ????
person kleinfreund    schedule 05.06.2013
comment
Спасибо ... стиль отображения CSS исправил это. - person Si8; 05.06.2013
comment
Спасибо @kleinfreund, использование «решения 3» помогло мне в Firefox 29.0.1 и IE10. - person hatsrumandcode; 22.05.2014
comment
@kleinfreund ! я использую chrome 39.0.2171.95, и когда я делаю выравнивание текста: по центру основного div, центры ul !! , так действительно ли эти хаки необходимы для современных браузеров? Ссылка: jsfiddle.net/8jsat2h9. - person Tenali_raman; 20.12.2014
comment
Я бы не назвал эти хаки. Возможно, последний вариант странный, но могут быть случаи, когда он вам понадобится. Какой у Вас вопрос? - person kleinfreund; 20.12.2014
comment
@kleinfreund У меня такое ощущение, что вы включили 4-е решение, просто для красоты :), как вы упомянули, для этого потребуются предварительные исправления. вопрос, который у меня был, находится в моем первоначальном комментарии, прикрепленном к скрипке. но на самом деле вам не обязательно отвечать на него, я как бы сам разобрался :D . отличный ответ однако! Благодарю . - person Tenali_raman; 20.12.2014
comment
@Tenali_raman Спасибо за демонстрацию. Я переработал его, чтобы показать все 4 решения рядом (и заметил, что решение 4 на самом деле не работает). Я все еще не понимаю ваш первоначальный вопрос. В чем проблема с этим? - person kleinfreund; 20.12.2014
comment
Я помещаю текст в ‹ul› поверх изображения, и у меня сработало только 4-е решение. - person wordsforthewise; 16.11.2016
comment
Я использую начальную загрузку, и первый метод работал даже без максимальной ширины, что аккуратно - person Joe Half Face; 26.01.2018
comment
Я пробую решение 5, но ul - это перенос строки, поэтому похоже, что у меня есть 3 столбца. Есть идеи, почему? - person gaefan; 18.03.2018
comment
@JeffO'Neill, я не понимаю, что ты имеешь в виду. У вас есть пример/фрагмент кода? - person kleinfreund; 18.03.2018
comment
@kleinfreund, я переключился на № 3, и это сработало. Я только что снова попробовал # 5, и теперь он работает, и я не могу воссоздать то, что я упоминал в своем предыдущем комментарии. Спасибо за великолепный пост! - person gaefan; 18.03.2018

Сделайте левое и правое поля вашего UL auto и назначьте ему ширину:

#headermenu ul {
    margin: 0 auto;
    width: 620px;
}

Редактировать: Как предложил kleinfreund, вы также можете выровнять контейнер по центру и дать ul отображение встроенного блока, но тогда вы также должны указать LI либо левое плавающее, либо встроенное отображение.

#headermenu { 
    text-align: center;
}
#headermenu ul { 
    display: inline-block;
}
#headermenu ul li {
    float: left; /* or display: inline; */
}
person Derek Henderson    schedule 05.06.2013
comment
Пункты меню (якоря) в #headermenu по ссылке, предоставленной автором, имеют float: left; присвоение. - person kleinfreund; 05.06.2013
comment
@kleinfreund, да, на его странице они есть, но не во фрагменте кода, который он вставил в вопрос. Не помешает прямо заявить об этом. - person Derek Henderson; 05.06.2013
comment
Возможно, вам следует использовать float в качестве примера, потому что пункты меню на его странице тоже не встроены. - person kleinfreund; 05.06.2013
comment
@kleinfreund, хорошо. У меня был поплавок в комментарии, но сейчас я его поменял. - person Derek Henderson; 05.06.2013

Вы можете проверить, что это решило вашу проблему...

    #headermenu ul{ 
        text-align: center;
    }
    #headermenu li { 
list-style-type: none;
        display: inline-block;
    }
    #headermenu ul li a{
        float: left;
    }

http://jsfiddle.net/thirtydot/VCZgW/

person Gaurang P    schedule 14.07.2015

person    schedule
comment
объясни что ты тут сделал! - person Suresh Karia; 01.08.2015