Сетка CSS делает макет из 3 столбцов с дочерними элементами

У меня есть следующая разметка:

<div class = "pagination">
 <a>Prev</a>
 <a>1</a>
 <a>2</a>
 <span>...</span>
 <a>12</a>
 <a>Next</a>
</div>

Я пытаюсь сделать макет из трех столбцов, где первый столбец — это Prev, второй столбец — 1 2 ... 12, а последний — Next, а средний столбец должен быть выровнен по центру, теперь я не могу обновить разметку, так как она автоматически генерируется приложением. Я пробовал со следующим:

.pagination {
    display: grid;
    grid-template-columns: 100px repeat(auto-fit, 20px) 100px;
}

А вот вторая колонка не распространяется целиком

Вы не можете сделать макет с 1 строкой и 3 столбцами здесь. Вы уверены, что flexbox недостаточно для ваших нужд?

Jared 30.03.2022 09:46

Вы не определяете 3 столбца, вы определяете динамическое количество столбцов в зависимости от ширины экрана.

connexo 30.03.2022 10:18
Улучшение производительности загрузки с помощью 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
2
56
6
Перейти к ответу Данный вопрос помечен как решенный

Ответы 6

Можешь попробовать так с flex?

HTML:

<div class = "pagination">
 <div>
   <a>Prev</a>
 </div>
 <div>
   <a>1</a>
   <a>2</a>
   <span>...</span>
   <a>12</a>
 </div>
 <div>
  <a>Next</a>
 </div>
</div>

CSS:

.pagination {
  display: flex;
  justify-content: space-between
}

https://jsfiddle.net/Danielprabhakaran_N/svkc30wg/

Если вы хотите получить такой же результат во flexbox, вот код:

.pagination {
    width: 100%;
    padding: 20px;
    background-color: #aaa;
    display: flex;
    align-items: stretch;
}
.pagination a {
    width: 40px;
    text-align: center;
}
.pagination a:first-child,
.pagination a:last-child {
    width: 100%;
}
.pagination a:first-child {
    text-align: left;
}
.pagination a:last-child {
    text-align: right;
}
<div class = "pagination">
 <a>Prev</a>
 <a>1</a>
 <a>2</a>
 <span>...</span>
 <a>12</a>
 <a>Next</a>
</div>

Один из вариантов — и обратите внимание, что мне очень не нравится такой подход — следующий:

/* Simple reset styles to normalise layout and base-sizes: */
*,
 ::before,
 ::after {
  box-sizing: border-box;
  font: normal 400 1rem/1.5 sans-serif;
  margin: 0;
  padding: 0;
}

/* defining the grid (obviously adjust sizing and layout to your taste: */
.pagination {
  display: grid;
  grid-template-areas: "prev pages next";
}

/* Selecting all <a> elements that are not the :first-child and
   and are also not the :last-child, and also the <span> elements: */
a:not(:first-child):not(:last-child),
span {
  /* displaying the contents of the selected elements as if their
     outer element (the elements selected) didn't exist or were
     'transparent' to CSS layout:*/
  display: contents;
  /* positioning the elements in the 'pages' area of the grid: */
  grid-area: pages;
}

[href = "#prev"] {
  grid-area: prev;
}

[href = "#next"] {
  grid-area: next;
}
<div class = "pagination">
  <a href = "#prev">Prev</a>
  <a href = "#">1</a>
  <a href = "#">2</a>
  <span>...</span>
  <a href = "#">12</a>
  <a href = "#next">Next</a>
</div>

Демонстрация скрипта JS.

Очевидно, как ясно показали другие, гибкий макет CSS является предпочтительным подходом, например:

/* simple CSS reset */
*,
::before,
::after {
  box-sizing: border-box;
  font: normal 400 1rem/1.5 sans-serif;
  margin: 0;
  padding: 0;
}

.pagination {
  display: flex;
  width: 90vw;
  /* setting the margin on the block-axis of the element, perpendicular to
     the 'text-flow' axis:*/
  margin-block: 1em;
  /* setting margin on the inline-axis (the 'text-flow' axis) of the
     element: */
  margin-inline: auto;
  /* shorthand for justify-content: center and align-content: center: */
  place-content: center;
  /* placing a 0.5em gap between adjacent siblings: */
  gap: 0.5em;
}

a:first-child {
  /* setting a margin of 'auto' to the a:first-child element's side
     which is at the end of its 'text-flow', so between the first-element
     and its following sibling: */
  margin-inline-end: auto;
}

a:last-child {
  /* similar to the above, but setting the margin between the a:last-child
     and its preceding sibling: */
  margin-inline-start: auto;
}
<div class = "pagination">
  <a href = "#prev">Prev</a>
  <a href = "#">1</a>
  <a href = "#">2</a>
  <span>...</span>
  <a href = "#">12</a>
  <a href = "#next">Next</a>
</div>

Демонстрация скрипта JS

Вот что я сделал

HTML:

<div class = "pagination">
    <a>Prev</a>
    <div class = "second-line">
        <a>1</a>
        <a>2</a>
        <span>...</span>
        <a>12</a>
    </div>
    <a>Next</a>
</div>

CSS:

.pagination{
    display: grid;
}

.pagination::after{
    content: '\a';
}

Добавьте строку .pagination::after{content: '\a';}, чтобы добавить разрыв строки, и добавьте div для второй строки, чтобы не добавлять разрыв строки, например, между <a>1</a> и <a>2</a>.

Ответ принят как подходящий

Используйте флексбокс:

.pagination{
  display: flex;
  gap: 10px;
}

.pagination a:first-child{
  margin-right: auto;
}

.pagination a:last-child{
  margin-left: auto;
}
<div class = "pagination">
 <a>Prev</a>
 <a>1</a>
 <a>2</a>
 <span>...</span>
 <a>12</a>
 <a>Next</a>
</div>

Это сработало, самый простой подход. Спасибо

nick 30.03.2022 10:23

Ты можешь попробовать:

<!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <meta http-equiv = "X-UA-Compatible" content = "IE=edge">
    <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
    <title>Ans dt 30-Mar-2022</title>
    <style>

    .pagination {
        display: grid;
        grid-template-columns: 100px 100px 100px;
        justify-items: center;
    }

    </style>
</head>
<body>
    <div class = "pagination">
        <a>Prev</a>
        <span>
            <a>1</a>
            <a>2</a>
            <span>...</span>
            <a>12</a>
        </span>
        <a>Next</a>
    </div>    

</body>
</html>

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