Использование CSS для центрирования гибких элементов независимо от размера экрана - PullRequest
0 голосов
/ 24 сентября 2018

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

Тело вопроса: Я создаювеб-сайт использует HTML и CSS в первый раз, и хотя я беру много учебников и ресурсов для чтения, я все еще не понимаю концепцию гибких элементов.На моем текущем веб-сайте у меня есть три изображения, выровненные по горизонтали, и они располагаются по центру при просмотре страницы на ноутбуке.Однако, когда я смотрю его на моем большом рабочем столе, все изображения выровнены по левому краю.Я просмотрел здесь десятки страниц, посвященных центрированию элементов в CSS, но пока ничего не имеет смысла - однако это может быть связано с моей наивностью при использовании CSS и HTML.Я разместил свой код CSS и HTML ниже.Есть ли в этом коде что-то, что неправильно выравнивает изображения по левому краю при расширении экрана?(Примечание: это мой первый вопрос о переполнении стека, и хотя я прочитал руководство по публикации вопросов, мне бы очень хотелось, чтобы вы высказали свое мнение о том, как я могу сделать это более понятным).Спасибо!(Кроме того, к вашему сведению, поскольку это мой первый пост, мне пока не разрешено вставлять изображения, иначе я бы получил скриншоты того, о чем я говорю).

/* Box Model */

*,
*:before,
*:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}


/* Containers */

.container {
  margin-left: auto;
  margin-right: auto;
}

.container.\31 25\25 {
  width: 100%;
  max-width: 100em;
  min-width: 80em;
}

.container.\37 5\25 {
  width: 60em;
}

.container.\35 0\25 {
  width: 40em;
}

.container.\32 5\25 {
  width: 20em;
}

.container {
  width: 80em;
}

@media screen and (max-width: 1680px) {
  .container.\31 25\25 {
    width: 100%;
    max-width: 100em;
    min-width: 80em;
  }
  .container.\37 5\25 {
    width: 60em;
  }
  .container.\35 0\25 {
    width: 40em;
  }
  .container.\32 5\25 {
    width: 20em;
  }
  .container {
    width: 80em;
  }
}

@media screen and (max-width: 1280px) {
  .container.\31 25\25 {
    width: 100%;
    max-width: 81.25em;
    min-width: 65em;
  }
  .container.\37 5\25 {
    width: 48.75em;
  }
  .container.\35 0\25 {
    width: 32.5em;
  }
  .container.\32 5\25 {
    width: 16.25em;
  }
  .container {
    width: 65em;
  }
}

@media screen and (max-width: 980px) {
  .container.\31 25\25 {
    width: 100%;
    max-width: 112.5%;
    min-width: 90%;
  }
  .container.\37 5\25 {
    width: 67.5%;
  }
  .container.\35 0\25 {
    width: 45%;
  }
  .container.\32 5\25 {
    width: 22.5%;
  }
  .container {
    width: 90%;
  }
}

@media screen and (max-width: 736px) {
  .container.\31 25\25 {
    width: 100%;
    max-width: 112.5%;
    min-width: 90%;
  }
  .container.\37 5\25 {
    width: 67.5%;
  }
  .container.\35 0\25 {
    width: 45%;
  }
  .container.\32 5\25 {
    width: 22.5%;
  }
  .container {
    width: 90% !important;
  }
}

@media screen and (max-width: 480px) {
  .container.\31 25\25 {
    width: 100%;
    max-width: 112.5%;
    min-width: 90%;
  }
  .container.\37 5\25 {
    width: 67.5%;
  }
  .container.\35 0\25 {
    width: 45%;
  }
  .container.\32 5\25 {
    width: 22.5%;
  }
  .container {
    width: 90% !important;
  }
}


/* Flex */

.flex {
  display: -ms-flexbox;
  -ms-flex-wrap: nowrap;
  -ms-flex-pack: justify;
  -moz-justify-content: center;
  -webkit-justify-content: center;
  -ms-justify-content: center;
  justify-content: center;
  align-items: center;
  display: -moz-flex;
  display: -webkit-flex;
  display: -ms-flex;
  display: flex;
  -moz-flex-wrap: nowrap;
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
  width: 100%;
  max-width: 900px;
  min-width: 500px;
}

.flex.flex-2 {
  -moz-justify-content: center;
  -webkit-justify-content: center;
  -ms-justify-content: center;
  justify-content: center;
}

.flex.flex-2 article {
  width: 100%;
}

@media screen and (max-width: 980px) {
  .flex.flex-2 article {
    width: 100%;
    margin-bottom: 3em;
    auto
  }
  .flex.flex-2 article:last-child {
    margin-bottom: 0;
    auto
  }
}

@media screen and (max-width: 480px) {
  .flex.flex-2 br {
    display: none;
  }
}


/* Box */

.box {
  border: solid 1px #dbdbdb;
  margin-bottom: 2em;
  padding: 1.5em;
}

.box> :last-child,
.box> :last-child> :last-child,
.box> :last-child> :last-child> :last-child {
  margin-bottom: 0;
}

.box.alt {
  border: 0;
  border-radius: 0;
  padding: 0;
}

.box.person {
  border: solid 1px #8dcca9;
  padding: 3em 1.5em;
}

.box.person h3 {
  margin: 0;
}

.box.person .image {
  margin-bottom: 1em;
}

.box.person .image img {
  max-width: 100%;
}
<!-- Main -->
<section id="main" class="wrapper">
  <div class="inner">
    <header class="align-center">
      <h2>A comprehensive collection of workshops, webinars, and resources for Belmont Forum researchers</h2>
    </header>

    <section id="three" class="wrapper align-center">
      <div class="inner">
        <div class="flex flex-2">
          <article>
            <div class="w3-circle">
              <img src="images/globe.jpg" alt="Pic 02" />
            </div>
            <header>
              <h3>By Country/Region</h3>
            </header>
            <footer>
              <a href="Data_Management_Trainings.md" target="_blank" class="button">Find Resources</a>
            </footer>
          </article>
          <article>
            <div class="w3-circle">
              <img src="images/computer.jpg" alt="Pic 01" />
            </div>
            <header>
              <h3>By Resource Type</h3>
            </header>
            <footer>
              <a href="http://bfe-inf.org/sites/default/files/doc-repository/Outline_Data_Skills_Curricula_Framework.pdf" target=_blank " class="button ">Find Resources</a>
							</footer>
						</article>
						<article>
							<div class="w3-circle ">
								<img src="images/business_woman.jpg " alt="globe " />
							</div>
							<header>
								<h3>By Role</h3>
							</header>
							<footer>
								<a href="http://bfe-inf.org/sites/default/files/doc-repository/Outline_Data_Skills_Curricula_Framework.pdf " target=_blank" class="button">Find Resources</a>
            </footer>
          </article>

        </div>
      </div>
    </section>

Ответы [ 2 ]

0 голосов
/ 25 сентября 2018

Я не знаю, правильно ли я понимаю ваш вопрос.Я попробовал это.Надеюсь, это поможет!

body {
  padding: 0;
  margin: 0;
}
label:hover {
  cursor: pointer;
}
#table {
  padding: 3em;
}
#table h2 {
  margin-bottom: 2em;
}
#table input[name="tcol"],
#table nav {
  display: none;
}
#table h2 {
  text-align: center;
  width: 100%;
}
#table nav {
  display: none;
  justify-content: center;
  padding: 0 1em;
}
#table nav > label {
  color: #339bf0;
  display: inline-block;
  padding: 1em;
}
#table table {
  border-collapse: separate;
  border-spacing: 0;
  overflow: hidden;
  width: 100%;
}
#table table td,
#table table th {
  padding: 1em;
  width: 33.33%;
  text-align: center;
}
#table table tbody > tr > td h3 {
  margin-bottom: 0.05em;
  text-align: center;
}
#table table tfoot > tr > td {
  text-align: center;
}
#table table.data-table.two-col td,
#table table.data-table.two-col th {
  width: 50%;
}
#table table.data-table.three-col td,
#table table.data-table.three-col th {
  width: 33.33%;
}
#table table.data-table.four-col td,
#table table.data-table.four-col th {
  width: 25%;
}
#table table.data-table.five-col td,
#table table.data-table.five-col th {
  width: 20%;
}
#table table.data-table.six-col td,
#table table.data-table.six-col th {
  width: 16.67%;
}
#table table.data-table.seven-col td,
#table table.data-table.seven-col th {
  width: 14.29%;
}
@media screen and (max-width: 768px) and (orientation: portrait) {
  #table {
    padding: 1em;
  }
  #table h2 {
    margin-bottom: 0;
  }
  #table nav {
    display: flex;
  }
  #table table th,
  #table table td {
    display: none;
    width: 100%;
  }
  #table table.data-table[class*="-col"] th,
  #table table.data-table[class*="-col"] td {
    width: 100%;
  }
  #table input:checked:nth-of-type(1) ~ nav label:nth-of-type(1) {
    border-bottom: 3px solid #000000;
    color: black;
  }
  #table input:checked:nth-of-type(1) ~ table tr > td:nth-of-type(1),
  #table input:checked:nth-of-type(1) ~ table tr > th:nth-of-type(1) {
    display: table-cell;
  }
  #table input:checked:nth-of-type(2) ~ nav label:nth-of-type(2) {
    border-bottom: 3px solid #000000;
    color: black;
  }
  #table input:checked:nth-of-type(2) ~ table tr > td:nth-of-type(2),
  #table input:checked:nth-of-type(2) ~ table tr > th:nth-of-type(2) {
    display: table-cell;
  }
  #table input:checked:nth-of-type(3) ~ nav label:nth-of-type(3) {
    border-bottom: 3px solid #000000;
    color: black;
  }
  #table input:checked:nth-of-type(3) ~ table tr > td:nth-of-type(3),
  #table input:checked:nth-of-type(3) ~ table tr > th:nth-of-type(3) {
    display: table-cell;
  }
}
<div id="table">
  <h2>A comprehensive collection of workshops, webinars, and resources for Belmont Forum researchers</h2>
  <input id="tcol1" name="tcol" type="radio" checked/>
  <input id="tcol2" name="tcol" type="radio" />
  <input id="tcol3" name="tcol" type="radio" />
  <nav>
    <label for="tcol1">Region</label>
    <label for="tcol2">Type</label>
    <label for="tcol3">Role</label>
  </nav>
  <table class="data-table">
    <colgroup>
      <col>
      <col>
      <col>
    </colgroup>
    <tbody>
      <tr>
        <td><img src="images/globe.jpg" alt="Pic 02" /></td>
        <td><img src="images/computer.jpg" alt="Pic 01" /></td>
        <td><img src="images/business_woman.jpg" alt="globe" /></td>
      </tr>
      <tr>
        <td>
          <h3>By Country/Region</h3>
        </td>
        <td>
          <h3>By Resource Type</h3>
        </td>
        <td>
          <h3>By Role</h3>
        </td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td>
          <h3><a href="Data_Management_Trainings.md" target ="_blank" class="button">Find Resources</a></h3>
        </td>
        <td>
          <h3><a href="http://bfe-inf.org/sites/default/files/doc-repository/Outline_Data_Skills_Curricula_Framework.pdf" target="_blank" class="button">Find Resources</a></h3>
        </td>
        <td>
          <h3><a href="http://bfe-inf.org/sites/default/files/doc-repository/Outline_Data_Skills_Curricula_Framework.pdf" target="_blank" class="button">Find Resources</a></h3>
        </td>
      </tr>
    </tfoot>
    
  </table>
</div>
0 голосов
/ 24 сентября 2018
.inner {
    display: flex;
    justify-content: center;
}

Ваш .flex .flex-2 div выравнивается по левому краю, потому что его родительский div .inner отображает его содержимое слева направо (это поведение по умолчанию для элемента блока), а ваш div привязан к определенной ширине.Flexbox полностью использует родительские контейнеры для выравнивания их дочерних элементов - justify-content & align-items может использоваться для центрирования ваших элементов от родительского элемента.:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...