Как централизовать CSS Grid по вертикали и горизонтали

body {
  background-color: hsl(210, 46%, 95%);
  font-size: 13px;
  font-family: "Barlow Semi Condensed", sans-serif;
  height: 100vh;
}

svg {
  position: absolute;
  justify-self: right;
  padding-right: 20px;
}

.attribution {
  font-size: 11px;
  text-align: center;
}
.attribution a {
  color: hsl(228, 45%, 44%);
}

.testimonialsmain {
  display: grid;
  grid-template-columns: auto auto auto auto;
  grid-template-rows: auto auto;
  gap: 20px;
  padding: 20px;
}

.testimonialitem {
  border-radius: 5px;
}
.testimonialitem:nth-child(3) {
  grid-row: span 2;
  background-color: hsl(0, 0%, 100%);
  padding: 20px;
  display: grid;
}

.testimonialitem:nth-child(1) {
  grid-column: span 2;
  background-color: hsl(263, 55%, 52%);
  color: hsl(0, 0%, 81%);
  padding: 20px;
  display: grid;

  width: auto;
}

.testimonialitem:nth-child(2) {
  background-color: hsl(217, 19%, 35%);
  color: hsl(0, 0%, 81%);
  padding: 20px;
  display: grid;

  width: auto;
}

.testimonialitem:nth-child(4) {
  background-color: hsl(0, 0%, 100%);
  padding: 20px;
  display: grid;

  width: auto;
}
.testimonialitem:nth-child(5) {
  grid-column: span 2;
  background-color: hsl(219, 29%, 14%);
  color: hsl(0, 0%, 81%);
  padding: 20px;
  display: grid;

  width: auto;
}

.card {
  display: grid;
  grid-template-columns: 1fr 6fr;
}

.pic {
  border-radius: 50%;
}

.intro {
  padding-top: 10px;
  font-size: large;
  z-index: 2;
}

.testimonial {
  padding-top: 10px;
}
<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8" />
    <meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
    <!-- displays site properly based on user's device -->

    <link
      rel = "icon"
      type = "image/png"
      sizes = "32x32"
      href = "./images/favicon-32x32.png"
    />

    <title>Frontend Mentor | Testimonials Grid</title>

    <!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
    <link rel = "stylesheet" href = "style.css" type = "text/css" />
    <link rel = "preconnect" href = "https://fonts.googleapis.com" />
    <link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin />
    <link
      href = "https://fonts.googleapis.com/css2?family=Barlow+Semi+Condensed:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap"
      rel = "stylesheet"
    />
  </head>
  <body>
    <div class = "main">
      <div class = "testimonialsmain">
        <div class = "testimonialitem">
          <svg width = "104" height = "102" xmlns = "http://www.w3.org/2000/svg">
            <path
              d = "M104 102V59.727H84.114c0-5.871.689-11.182 2.068-15.933 1.379-4.75 3.42-9.287 6.125-13.61C95.01 25.86 98.909 22.257 104 19.375V0c-9.758 4.27-17.712 9.874-23.864 16.813-6.151 6.939-10.712 14.545-13.681 22.818C63.485 47.904 62 59.941 62 75.74V102h42zm-62 0V59.727H22.114c0-5.871.689-11.182 2.068-15.933 1.379-4.75 3.42-9.287 6.125-13.61C33.01 25.86 36.909 22.257 42 19.375V0c-9.652 4.27-17.58 9.874-23.784 16.813C12.01 23.752 7.424 31.358 4.455 39.631 1.485 47.904 0 59.941 0 75.74V102h42z"
              fill = "#A775F1"
              fill-rule = "nonzero"
            />
          </svg>
          <div class = "card">
            <img src = "./images/image-daniel.jpg" class = "pic" />
            Daniel Clifford <br />
            Verified Graduate
          </div>

          <div class = "intro">
            I received a job offer mid-course, and the subjects I learned were
            current, if not more so, in the company I joined. I honestly feel I
            got every penny’s worth.
          </div>
          <div class = "testimonial">
            “ I was an EMT for many years before I joined the bootcamp. I’ve
            been looking to make a transition and have heard some people who had
            an amazing experience here. I signed up for the free intro course
            and found it incredibly fun! I enrolled shortly thereafter. The next
            12 weeks was the best - and most grueling - time of my life. Since
            completing the course, I’ve successfully switched careers, working
            as a Software Engineer at a VR startup. ”
          </div>
        </div>

        <div class = "testimonialitem">
          <div class = "card">
            <img src = "./images/image-jonathan.jpg" class = "pic" /> Jonathan
            Walters <br />
            Verified Graduate
          </div>

          <div class = "intro">
            The team was very supportive and kept me motivated
          </div>
          <div class = "testimonial">
            “ I started as a total newbie with virtually no coding skills. I now
            work as a mobile engineer for a big company. This was one of the
            best investments I’ve made in myself. ”
          </div>
        </div>

        <div class = "testimonialitem">
          <div class = "card">
            <img src = "./images/image-kira.jpg" class = "pic" /> Kira Whittle
            <br />
            Verified Graduate
          </div>
          <div class = "intro">
            Such a life-changing experience. Highly recommended!
          </div>
          <div class = "testimonial">
            “ Before joining the bootcamp, I’ve never written a line of code. I
            needed some structure from professionals who can help me learn
            programming step by step. I was encouraged to enroll by a former
            student of theirs who can only say wonderful things about the
            program. The entire curriculum and staff did not disappoint. They
            were very hands-on and I never had to wait long for assistance. The
            agile team project, in particular, was outstanding. It took my
            learning to the next level in a way that no tutorial could ever
            have. In fact, I’ve often referred to it during interviews as an
            example of my developent experience. It certainly helped me land a
            job as a full-stack developer after receiving multiple offers. 100%
            recommend! ”
          </div>
        </div>
        <div class = "testimonialitem">
          <div class = "card">
            <img src = "./images/image-jeanette.jpg" class = "pic" /> Jeanette
            Harmon <br />
            Verified Graduate
          </div>
          <div class = "intro">An overall wonderful and rewarding experience</div>
          <div class = "testimonial">
            “ Thank you for the wonderful experience! I now have a job I really
            enjoy, and make a good living while doing something I love. ”
          </div>
        </div>
        <div class = "testimonialitem">
          <div class = "card">
            <img src = "./images/image-patrick.jpg" class = "pic" /> Patrick Abrams
            <br />
            Verified Graduate
          </div>
          <div class = "intro">
            Awesome teaching support from TAs who did the bootcamp themselves.
            Getting guidance from them and learning from their experiences was
            easy.
          </div>
          <div class = "testimonial">
            “ The staff seem genuinely concerned about my progress which I find
            really refreshing. The program gave me the confidence necessary to
            be able to go out in the world and present myself as a capable
            junior developer. The standard is above the rest. You will get the
            personal attention you need from an incredible community of smart
            and amazing people. ”
          </div>
        </div>
      </div>

      <div class = "attribution">
        Challenge by
        <a href = "https://www.frontendmentor.io?ref=challenge" target = "_blank"
          >Frontend Mentor</a
        >. Coded by <a href = "#">Aparna Gopalakrishnan</a>.
      </div>
    </div>
  </body>
</html>

Я создал сетку с 3 столбцами и 2 строками. Но не в состоянии централизовать его по вертикали и горизонтали.

Может ли кто-нибудь предложить решение, которое будет работать с написанным мной кодом?

Я пробовал использовать различные свойства, такие как align-items, align-self, align-content и т. д. Также ссылался на некоторые решения на этом форуме. У меня пока ничего не получалось. прокладка работает. Но, исходя из моих базовых знаний, я понимаю, что это не лучший дизайн для адаптивной страницы.

Теперь сетка расположена вверху страницы. Ожидаемый результат — переместить ее вниз к середине страницы, как показано на снимке экрана ниже.

Пожалуйста, предоставьте фрагмент кода вместо ссылки на ваш репозиторий GitHub. Ссылки могут потерять актуальность по какой-либо причине, и этот пост больше не будет актуален для будущего пользователя (более того, никто не хочет клонировать репозиторий, чтобы помочь).

Symtox 21.06.2024 10:29

Я включил код здесь. Пожалуйста, проверьте это и дайте мне знать.

Aparna 21.06.2024 16:38

Если кто-то может открыть этот вопрос, я мог бы добавить ответ о том, как я решил свою проблему.

Aparna 26.06.2024 15:24

Кто-то снова открыл его

Symtox 26.06.2024 15:44
Улучшение производительности загрузки с помощью 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 страниц, которые помогут...
2
4
97
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Установите свойство align-content и свойство justify-content в центр. Убедитесь, что есть свободное пространство по горизонтали и вертикали, иначе свойства не будут эффективными.

Извините, что мой код не был добавлен при первой отправке. Не могли бы вы проверить добавленный мной код и сообщить мне, куда я могу добавить предложенные вами свойства? Думаю, я уже пробовал это однажды, основываясь на предложении из другого поста на этом форуме.

Aparna 21.06.2024 16:37

Добавьте свойства в контейнер сетки. После этого отрегулируйте верхний край так, чтобы у вас было пространство вверху, а также отрегулируйте верхний край справа и слева, чтобы у вас также было немного пробелов. Вот как я изменил ваш контейнер сетки. ` .testimonialsmain { display:grid; столбцы-шаблона сетки: повторение (4, авто); выровнять-контент: центр; оправдание-содержание: центр; маржа-верх: 10em; разрыв: 20 пикселей; отступ: 20 пикселей; поле слева: 150 пикселей; поле справа: 200 пикселей; поле справа: 200 пикселей; }`

Stephen Mutheu 21.06.2024 19:10

@StephenMutheu, пожалуйста, добавьте код своего решения в качестве примера из ОП.

IT Guy 22.06.2024 10:12

Можете ли вы показать мне, как это сделать, братан, я боролся с этим, и это ограничивает меня в помощи. Я нашел около 5 способов сделать это, но ни один из них не сработал!

Stephen Mutheu 23.06.2024 08:03

Подожди, я говорил о том, «как правильно ответить на вопрос в Stackoverflow»… Похоже, ты говоришь о том, как центрировать весь контейнер… Что ты имеешь в виду, братан? Оба тоже я готов помочь

IT Guy 23.06.2024 10:28
Ответ принят как подходящий

Решение

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

.main {
  width: 100vw;
  height: 100vh;
}

Если вы хотите просмотреть это с помощью мобильного телефона, вы можете сделать это:

.main {
  width: 100dvw;
  height: 100dvh;
}

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

.main {
  width: 100vw;
  height: 100vh;
  display: grid;
  justify-content: center;
  align-content: center;
}

По умолчанию ширина div будет равна 100 %, поэтому вам нужно установить max-width для вашего контента следующим образом:

.testimonialsmain {
  max-width: 1000px;
  /* other styles */
}

Вы можете обратиться к этому для своего решения.

*,
*::before,
*::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: hsl(210, 46%, 95%);
  font-size: 13px;
  font-family: "Barlow Semi Condensed", sans-serif;
  height: 100vh;
}

svg {
  position: absolute;
  justify-self: right;
  padding-right: 20px;
}

.attribution {
  font-size: 11px;
  text-align: center;
}

.attribution a {
  color: hsl(228, 45%, 44%);
}

.main {
  width: 100vw;
  height: 100vh;
  display: grid;
  justify-content: center;
  align-content: center;
}

.testimonialsmain {
  max-width: 1000px;
  display: grid;
  grid-template-columns: auto auto auto auto;
  grid-template-rows: auto auto;
  gap: 20px;
  padding: 20px;
}

.testimonialitem {
  border-radius: 5px;
}

.testimonialitem:nth-child(3) {
  grid-row: span 2;
  background-color: hsl(0, 0%, 100%);
  padding: 20px;
  display: grid;
}

.testimonialitem:nth-child(1) {
  grid-column: span 2;
  background-color: hsl(263, 55%, 52%);
  color: hsl(0, 0%, 81%);
  padding: 20px;
  display: grid;
  width: auto;
}

.testimonialitem:nth-child(2) {
  background-color: hsl(217, 19%, 35%);
  color: hsl(0, 0%, 81%);
  padding: 20px;
  display: grid;
  width: auto;
}

.testimonialitem:nth-child(4) {
  background-color: hsl(0, 0%, 100%);
  padding: 20px;
  display: grid;
  width: auto;
}

.testimonialitem:nth-child(5) {
  grid-column: span 2;
  background-color: hsl(219, 29%, 14%);
  color: hsl(0, 0%, 81%);
  padding: 20px;
  display: grid;
  width: auto;
}

.card {
  display: grid;
  grid-template-columns: 1fr 6fr;
}

.pic {
  border-radius: 50%;
}

.intro {
  padding-top: 10px;
  font-size: large;
  z-index: 2;
}

.testimonial {
  padding-top: 10px;
}
<div class = "main">
  <div class = "testimonialsmain">
    <div class = "testimonialitem">
      <svg width = "104" height = "102" xmlns = "http://www.w3.org/2000/svg">
            <path
              d = "M104 102V59.727H84.114c0-5.871.689-11.182 2.068-15.933 1.379-4.75 3.42-9.287 6.125-13.61C95.01 25.86 98.909 22.257 104 19.375V0c-9.758 4.27-17.712 9.874-23.864 16.813-6.151 6.939-10.712 14.545-13.681 22.818C63.485 47.904 62 59.941 62 75.74V102h42zm-62 0V59.727H22.114c0-5.871.689-11.182 2.068-15.933 1.379-4.75 3.42-9.287 6.125-13.61C33.01 25.86 36.909 22.257 42 19.375V0c-9.652 4.27-17.58 9.874-23.784 16.813C12.01 23.752 7.424 31.358 4.455 39.631 1.485 47.904 0 59.941 0 75.74V102h42z"
              fill = "#A775F1"
              fill-rule = "nonzero"
            />
          </svg>
      <div class = "card">
        <img src = "./images/image-daniel.jpg" class = "pic" /> Daniel Clifford <br /> Verified Graduate
      </div>

      <div class = "intro">
        I received a job offer mid-course, and the subjects I learned were current, if not more so, in the company I joined. I honestly feel I got every penny’s worth.
      </div>
      <div class = "testimonial">
        “ I was an EMT for many years before I joined the bootcamp. I’ve been looking to make a transition and have heard some people who had an amazing experience here. I signed up for the free intro course and found it incredibly fun! I enrolled shortly thereafter.
        The next 12 weeks was the best - and most grueling - time of my life. Since completing the course, I’ve successfully switched careers, working as a Software Engineer at a VR startup. ”
      </div>
    </div>

    <div class = "testimonialitem">
      <div class = "card">
        <img src = "./images/image-jonathan.jpg" class = "pic" /> Jonathan Walters <br /> Verified Graduate
      </div>

      <div class = "intro">
        The team was very supportive and kept me motivated
      </div>
      <div class = "testimonial">
        “ I started as a total newbie with virtually no coding skills. I now work as a mobile engineer for a big company. This was one of the best investments I’ve made in myself. ”
      </div>
    </div>

    <div class = "testimonialitem">
      <div class = "card">
        <img src = "./images/image-kira.jpg" class = "pic" /> Kira Whittle
        <br /> Verified Graduate
      </div>
      <div class = "intro">
        Such a life-changing experience. Highly recommended!
      </div>
      <div class = "testimonial">
        “ Before joining the bootcamp, I’ve never written a line of code. I needed some structure from professionals who can help me learn programming step by step. I was encouraged to enroll by a former student of theirs who can only say wonderful things about
        the program. The entire curriculum and staff did not disappoint. They were very hands-on and I never had to wait long for assistance. The agile team project, in particular, was outstanding. It took my learning to the next level in a way that no
        tutorial could ever have. In fact, I’ve often referred to it during interviews as an example of my developent experience. It certainly helped me land a job as a full-stack developer after receiving multiple offers. 100% recommend! ”
      </div>
    </div>
    <div class = "testimonialitem">
      <div class = "card">
        <img src = "./images/image-jeanette.jpg" class = "pic" /> Jeanette Harmon <br /> Verified Graduate
      </div>
      <div class = "intro">An overall wonderful and rewarding experience</div>
      <div class = "testimonial">
        “ Thank you for the wonderful experience! I now have a job I really enjoy, and make a good living while doing something I love. ”
      </div>
    </div>
    <div class = "testimonialitem">
      <div class = "card">
        <img src = "./images/image-patrick.jpg" class = "pic" /> Patrick Abrams
        <br /> Verified Graduate
      </div>
      <div class = "intro">
        Awesome teaching support from TAs who did the bootcamp themselves. Getting guidance from them and learning from their experiences was easy.
      </div>
      <div class = "testimonial">
        “ The staff seem genuinely concerned about my progress which I find really refreshing. The program gave me the confidence necessary to be able to go out in the world and present myself as a capable junior developer. The standard is above the rest. You
        will get the personal attention you need from an incredible community of smart and amazing people. ”
      </div>
    </div>
  </div>

  <div class = "attribution">
    Challenge by
    <a href = "https://www.frontendmentor.io?ref=challenge" target = "_blank">Frontend Mentor</a
        >. Coded by <a href = "#">Aparna Gopalakrishnan</a>.
  </div>
</div>

Бонус

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

*, *::before, *::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

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