Подтвердить что ты не робот

Как центрировать несколько div внутри контейнера в CSS

Я тестирую центр делителя, как стиль окна метро. если вы проверите следующий код:

.container {
    height: 300px;
    width: 70%;
    background: #EEE;
    margin: 10px auto;
    position: relative;
}
.block {
    background: green;
    height: 100px;
    width: 100px;
    float: left;
    margin: 10px;
}
<div class="container">
  <div class="block">1. name of the company</div>
  <div class="block">2. name of the company</div>
  <div class="block">3. name of the company</div>
  <div class="block">4. name of the company</div>
  <div class="block">5. name of the company</div>
  <div class="block">6. name of the company</div>
  <div class="block">7. name of the company</div>
  <div class="block">8. name of the company</div>
</div>
4b9b3361

Ответ 1

Мой предыдущий ответ показал откровенно устаревший метод (он все еще работает, есть только лучшие способы добиться этого). По этой причине я обновляю его, чтобы включить более современное решение flexbox.

Поддержите его здесь; в большинстве сред его безопасно использовать.

Это использует преимущества:

  • display: flex: показать этот элемент с поведением flexbox
  • justify-content: center Выровнять внутренние элементы по центру вдоль главной оси контейнера
  • flex-wrap: wrap Убедитесь, что внутренние элементы автоматически оборачиваются внутри контейнера (не вырывайтесь из него)

Примечание: как обычно с HTML & CSS, это только один из многих способов получить желаемый результат. Внимательно изучите, прежде чем выбрать способ, который соответствует вашим требованиям.

.container {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    width: 70%;
    background: #eee;
    margin: 10px auto;
    position: relative;
    text-align:center;
}

.block {
    background: green;
    height: 100px;
    width: 100px;
    margin: 10px;
}
<div class="container">
    <div class="block">1. name of the company</div>
    <div class="block">2. name of the company</div>
    <div class="block">3. name of the company</div>
    <div class="block">4. name of the company</div>
    <div class="block">5. name of the company</div>
    <div class="block">6. name of the company</div>
    <div class="block">7. name of the company</div>
    <div class="block">8. name of the company</div>
</div>

Ответ 2

если вы измените стиль в элементе .block, поэтому вместо float:left; вы используете display:inline-block;, затем вы можете добавить text-align:center в .container

Пример

Ответ 3

Итак, в основном ваш CSS нуждается в этих изменениях

.container { text-align:center; }
.block { display:inline-block; *display:inline; zoom:1; vertical-align:top; }

чтобы сделать CSS совместимым с IE7.

Чтобы выровнять нижние плитки с левой стороны, необходим некоторый javascript. Из-за . QuerySelector() обратная совместимость: везде работает, включая IE8 +; для упрощения и совместимости с IE7 jQuery настоятельно рекомендуется:

if (!window.addEventListener) {
    window.addEventListener = function (type, listener, useCapture) {
        attachEvent('on' + type, function () {
            listener(event);
        });
    };
}
window.addEventListener('load', makePaddings, false);
window.addEventListener('resize', makePaddings, false);

function makePaddings() {
    var container = document.querySelector('.container');
    var blocks = document.querySelectorAll('.block');
    var br = [],
        max = 0,
        i = 0;
    var top = blocks[0].getBoundingClientRect().top;
    while (blocks[i] && blocks[i].getBoundingClientRect().top == top) {
        i++;
    }
    var show = blocks.length % i ? i - blocks.length % i : 0; /* how many paddings are needed */
    var paddings = document.querySelectorAll('.padding');
    if (paddings.length < show) { // add missing paddings
        i = show - paddings.length;
        while (i--) {
            var elem = document.createElement('div');
            elem.className = 'padding';
            elem.style.visibility = 'hidden';
            container.appendChild(elem);
        }
        paddings = document.querySelectorAll('.padding');
    }
    for (i = 0; i < paddings.length; i++) {
        paddings[i].style.display = (i < show) ? 'inline-block' : 'none';
    }
}

jsfiddle

Ответ 4

Теперь вы можете использовать Flexbox свойство как основу для ваших макетов. Это позволит вам больше контролировать дочерние элементы.

.container {
    width: 70%;
    background: #EEE;
    margin: 10px auto;
    position: relative;
    display:flex;
    flex-wrap:wrap;
    justify-content:center;
}
.block {
    background: green;
    height: 100px;
    width: 100px;
    margin: 10px;
}
<div class="container">
  <div class="block">1. name of the company</div>
  <div class="block">2. name of the company</div>
  <div class="block">3. name of the company</div>
  <div class="block">4. name of the company</div>
  <div class="block">5. name of the company</div>
  <div class="block">6. name of the company</div>
  <div class="block">7. name of the company</div>
  <div class="block">8. name of the company</div>
</div>

Ответ 5

.container {
  background: lightgrey;
  height: auto;
  width: 70%;

  margin: 10px auto;
  position: relative;
  
  display: flex;
  flex-wrap: wrap;  
  justify-content: space-around;
}
.block {
  background: green;
  height: 100px;
  width: 100px;
  
  margin: 10px;
}
<div class="container">
  <div class="block">1. name of the company</div>
  <div class="block">2. name of the company</div>
  <div class="block">3. name of the company</div>
  <div class="block">4. name of the company</div>
  <div class="block">5. name of the company</div>
  <div class="block">6. name of the company</div>
  <div class="block">7. name of the company</div>
  <div class="block">8. name of the company</div>
</div>

Ответ 6

<body>

<div class="container">
       <div style="width:78%; margin:0 auto;">
        <div class="block">1. name of the company</div>
        <div class="block">2. name of the company</div>
        <div class="block">3. name of the company</div>
        <div class="block">4. name of the company</div>
        <div class="block">5. name of the company</div>
        <div class="block">6. name of the company</div>
        <div class="block">7. name of the company</div>
        <div class="block">8. name of the company</div>
    </div>
</div>
</body>

Попробуйте этот div "<div style="width:78%; margin:0 auto;">"