Позиционирование элемента в таблице в соответствии с другим содержимым - PullRequest
0 голосов
/ 05 февраля 2020

Проблема

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

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

Чего я надеюсь достичь

Я бы хотел, чтобы две кнопки центрировались в своей ячейке посередине, чтобы соответствовать середине разного размера содержимого.

Я использую bootstrap 4, я знаю, что вы можете использовать align-center, но, похоже, это не сработает. Обычно я бы опубликовал код, но на самом деле было бы проще показать картинку, чтобы объяснить, что я имею в виду.

Table

Теперь, как вы можете видеть эти две кнопки Я хочу go к центру их клеток, чтобы соответствовать столбцу ингредиентов.

То, что я пробовал

Я пробовал различные методы с использованием начальной загрузки align-middle для кнопок, но они просто остаются в верхней части ячейки.

Этот вопрос, возможно, задавался ранее, но каждый вопрос, который я нахожу в стеке, я изо всех сил пытаюсь найти тот, который соответствует моему конкретному сценарию c, поэтому, если он был опубликован ранее, пожалуйста, обязательно связать меня и закрыть вопрос.

РЕДАКТИРОВАТЬ

Отображение кода не имело бы смысла и выглядело бы вне контекста, если бы я не опубликовал код для модели, вида, контроллера и js файл, который кажется слишком сложным, учитывая, что на вопрос можно ответить, основываясь только на контексте.

Ответы [ 2 ]

1 голос
/ 05 февраля 2020

Вертикальное центрирование является поведением по умолчанию в большинстве, если не во всех браузерах. Другими словами, если ваши кнопки не центрированы вертикально относительно длинного текста в ячейке рядом с ними, вы написали некоторый код для удаления вертикального центрирования (или вы используете чужой код, который останавливает вертикальное центрирование).

Я бы порекомендовал открыть вашу страницу в Chrome, щелкнуть правой кнопкой мыши по одной из ваших кнопок, которые не центрированы по вертикали, выбрать «осмотреть», а затем найти TD в проверяемом HTML, который оборачивает это нажав на этот элемент TD, и глядя на его CSS в инспекторе. TD может иметь какой-то стиль, который мешает его вертикальному центрированию. Удалите или переопределите этот стиль в своем коде CSS (просто снимите этот флажок в инспекторе Chrome, чтобы проверить, чтобы убедиться, что вы выбрали правильный стиль), и у вас все получится.

Например, скопируйте этот код в пустой HTML файл, а затем откройте его в браузере. Все ячейки должны быть вертикально центрированы, потому что ни один код в этом примере не говорит ячейкам вести себя иначе. Вы можете ПРОВЕРИТЬ кнопки в Chrome в моем примере - и, что более важно, TD, обертывающий их - чтобы увидеть, что по умолчанию CSS, и это должно дать вам представление о том, что CSS в вашем Нужно изменить собственный код и как его изменить.

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
</head>
<body>
    <table>
        <tr>
            <td>
                First cell.
            </td>
            <td>
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
            </td>
            <td>
                <button>First button</button><br/>
                <button>Second button</button>
            </td>
        </tr>
        <tr>
            <td>
                First cell.
            </td>
            <td>
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
                Second cell with tons of text. Second cell with tons of text. Second cell with tons of text. Second cell with tons of text.
            </td>
            <td>
                <button>First button</button><br/>
                <button>Second button</button>
            </td>
        </tr>
    </table>
</body>
</html>
0 голосов
/ 05 февраля 2020

Как насчет вертикальное выравнивание ?

<- В зависимости от реализации, также <a href="https://www.w3schools.com/tags/att_td_valign.asp" rel="nofollow noreferrer"> valign для td .--> Согласно комментарию ниже. эта опция устарела.

Если это не поможет, пожалуйста, оставьте свой код.

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