HTML / CSS: выравнивание вкладок по центру

Проблема: в приведенном ниже html / css вкладки отображаются нормально, но я хотел бы выровнять их по центру. Я пробовал разные способы, но они все еще выравниваются по левому краю. Как я могу выровнять три вкладки по центру и сохранить их встроенным блоком? Любая помощь приветствуется, спасибо.

Я также приложил картинку для справки. HTML / CSS: выравнивание вкладок по центру

main {
  min-width: 320px;
  max-width: 1000px;
  padding: 50px;
  margin: 0 auto;
  background: #fff;
}

section {
  display: none;
  padding: 20px 0 0;
  border-top: 1px solid #ddd;
}

.tabs {
  display: none;
  width: 100%;
  margin: 0 auto;
}

label {
  display: inline-block;
  margin: 0 auto;
  padding: 15px 25px;
  text-align: center;
  color: #bbb;
}

label[for*='1']:before {
  content: ;
}

label[for*='2']:before {
  content: ;
}

label[for*='3']:before {
  content: ;
}

label:hover {
  color: #888;
  cursor: pointer;
}

.tabs:checked+label {
  color: #555;
  border-bottom: 2px solid orange;
}

#tab1:checked~#content1,
#tab2:checked~#content2,
#tab3:checked~#content3 {
  display: block;
}
<main>
  <input class = "tabs" id = "tab1" type = "radio" name = "tabs" checked>
  <label for = "tab1">Tab 1</label>

  <input class = "tabs" id = "tab2" type = "radio" name = "tabs">
  <label for = "tab2">Tab 2</label>

  <input class = "tabs" id = "tab3" type = "radio" name = "tabs">
  <label for = "tab3">Tab 3</label>
  <section id = "content1">
    <img src = "/images/autocode.jpeg" alt = "Doctor Icon" class = "key-modules- 
        innter-image" height = "180" width = "auto">
    <h1 class = "key-modules-inner-div-header">Tab 2</h1>
    <p class = "key-modules-inner-div-paragraph">random text will go here
    </p>
    <a href = "/align-providers">
      <button type = "button" name = "button" class = "learn-button">Learn 
         more</button>
    </a>
  </section>

  <section id = "content2">
    <img src = "/images/autocode.jpeg" alt = "Doctor Icon" class = "key-modules- 
        innter-image" height = "180" width = "auto">
    <h1 class = "key-modules-inner-div-header">Tab 3</h1>
    <p class = "key-modules-inner-div-paragraph">random text will go here
    </p>
    <a href = "/align-providers">
      <button type = "button" name = "button" class = "learn-button">Learn 
         more</button>
    </a>
  </section>
  <section id = "content3">
    <img src = "/images/autocode.jpeg" alt = "Doctor Icon" class = "key-modules- 
        innter-image" height = "180" width = "auto">
    <h1 class = "key-modules-inner-div-header">Tab 3</h1>
    <p class = "key-modules-inner-div-paragraph">random text will go here
    </p>
    <a href = "/align-providers">
      <button type = "button" name = "button" class = "learn-button">Learn 
         more</button>
    </a>
  </section>
</main>
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Введение в CSS
Введение в CSS
CSS является неотъемлемой частью трех основных составляющих front-end веб-разработки.
Как выровнять Div по центру?
Как выровнять Div по центру?
Чтобы выровнять элемент <div>по горизонтали и вертикали с помощью CSS, можно использовать комбинацию свойств и значений CSS. Вот несколько методов,...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Travel Booking Angular Template один из лучших Travel & Tour booking template in the world. 30+ валидированных HTML5 страниц, которые помогут...
0
0
2 605
4

Ответы 4

Вы можете обернуть вкладки в div, а затем установить для оболочки css значение margin: auto и width: 20% или что-то еще, что удерживает их в строке.

Вот мой подход с использованием Flexbox.

Я добавил несколько держателей и код css

main {
  min-width: 320px;
  max-width: 1000px;
  padding: 50px;
  margin: 0 auto;
  background: #fff;
}

section {
  display: none;
  padding: 20px 0 0;
  border-top: 1px solid #ddd;
}

.tabs {
  display: none;
  margin: 0 auto;
}

label {
  padding: 15px 25px;
  text-align: center;
  color: #bbb;
  display: flex;
  border: 1px solid blue;
  align-self: center;
}

label[for*='1']:before {
  content: ;
}

label[for*='2']:before {
  content: ;
}

label[for*='3']:before {
  content: ;
}

label:hover {
  color: #888;
  cursor: pointer;
}

.tabs-holder {
  display: flex;
  align-items: center;
  flex-direction: column;
  border: 1px solid red;
}

.tabs-grouper {
  display: flex;
  flex-direction: row;
  border: 1px solid green;
}
<div class = "tabs-holder">
  <div class = "tabs-grouper">
    <input class = "tabs" id = "tab1" type = "radio" name = "tabs" checked>
    <label for = "tab1">Tab 1</label>

    <input class = "tabs" id = "tab2" type = "radio" name = "tabs">
    <label for = "tab2">Tab 2</label>

    <input class = "tabs" id = "tab3" type = "radio" name = "tabs">
    <label for = "tab3">Tab 3</label>
  </div>
</div>

Я использую всегда хороший чит, центральные теги!

<center>
  <input class = "tabs" id = "tab1" type = "radio" name = "tabs" checked>
  <label for = "tab1">Tab 1</label>

  <input class = "tabs" id = "tab2" type = "radio" name = "tabs">
  <label for = "tab2">Tab 2</label>

  <input class = "tabs" id = "tab3" type = "radio" name = "tabs">
  <label for = "tab3">Tab 3</label>
</center>

Привет @awtrimpe - спасибо за подсказку. Всегда приятно узнать что-то новое. Это работает, но, к сожалению, все центрирует. Мне нужны только три входа по центру. Я переместил теги в этот раздел, но нарушил логику. Секунды (1-3) больше не открываются, если я это сделаю.

AndrewK 16.07.2018 22:07

@AndrewK Не используйте <center>, он устарел много лет назад.

Ason 16.07.2018 22:21

Просто добавьте text-align: center в main, а затем сбросьте все на section с помощью text-align:left.

Это повлияет на inline-block элементы, но не на то, чтобы ваш section был block, хотя, поскольку потомки могут унаследовать его, сброс настроек позаботится об этом.

Фрагмент стека

main {
  min-width: 320px;
  max-width: 1000px;
  padding: 50px;
  margin: 0 auto;
  background: #fff;
  text-align: center;                   /*  added  */
}

section {
  display: none;
  padding: 20px 0 0;
  border-top: 1px solid #ddd;
  text-align: left;                     /*  added  */
}

.tabs {
  display: none;
  width: 100%;
  margin: 0 auto;
}

label {
  display: inline-block;
  margin: 0 auto;
  padding: 15px 25px;
  text-align: center;
  color: #bbb;
}

label[for*='1']:before {
  content: ;
}

label[for*='2']:before {
  content: ;
}

label[for*='3']:before {
  content: ;
}

label:hover {
  color: #888;
  cursor: pointer;
}

.tabs:checked+label {
  color: #555;
  border-bottom: 2px solid orange;
}

#tab1:checked~#content1,
#tab2:checked~#content2,
#tab3:checked~#content3 {
  display: block;
}
<main>
  <input class = "tabs" id = "tab1" type = "radio" name = "tabs" checked>
  <label for = "tab1">Tab 1</label>

  <input class = "tabs" id = "tab2" type = "radio" name = "tabs">
  <label for = "tab2">Tab 2</label>

  <input class = "tabs" id = "tab3" type = "radio" name = "tabs">
  <label for = "tab3">Tab 3</label>
  <section id = "content1">
    <img src = "/images/autocode.jpeg" alt = "Doctor Icon" class = "key-modules- 
        innter-image" height = "180" width = "auto">
    <h1 class = "key-modules-inner-div-header">Tab 2</h1>
    <p class = "key-modules-inner-div-paragraph">random text will go here
    </p>
    <a href = "/align-providers">
      <button type = "button" name = "button" class = "learn-button">Learn 
         more</button>
    </a>
  </section>

  <section id = "content2">
    <img src = "/images/autocode.jpeg" alt = "Doctor Icon" class = "key-modules- 
        innter-image" height = "180" width = "auto">
    <h1 class = "key-modules-inner-div-header">Tab 3</h1>
    <p class = "key-modules-inner-div-paragraph">random text will go here
    </p>
    <a href = "/align-providers">
      <button type = "button" name = "button" class = "learn-button">Learn 
         more</button>
    </a>
  </section>
  <section id = "content3">
    <img src = "/images/autocode.jpeg" alt = "Doctor Icon" class = "key-modules- 
        innter-image" height = "180" width = "auto">
    <h1 class = "key-modules-inner-div-header">Tab 3</h1>
    <p class = "key-modules-inner-div-paragraph">random text will go here
    </p>
    <a href = "/align-providers">
      <button type = "button" name = "button" class = "learn-button">Learn 
         more</button>
    </a>
  </section>
</main>

Другие вопросы по теме