Как центрировать div
- User
Как центрировать div
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Как центрировать div
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Центрирование div зависит от контекста (горизонтально/вертикально) и типа центрирования (блок/содержимое). Вот основные методы:
Способ 1: Через margin: auto (если задана ширина)
div {
width: 300px; /* обязательная ширина */
margin: 0 auto; /* автоматические отступы по бокам */
}
Способ 2: Flexbox (рекомендуется)
.parent {
display: flex;
justify-content: center; /* центрирование по горизонтали */
}
Способ 3: CSS Grid
.parent {
display: grid;
justify-content: center; /* для сетки */
}
Способ 1: Flexbox
.parent {
display: flex;
justify-content: center; /* горизонталь */
align-items: center; /* вертикаль */
height: 100vh; /* высота родителя (например, вся высота экрана) */
}
Способ 2: CSS Grid
.parent {
display: grid;
place-items: center; /* сокращение для выравнивания по обоим осям */
height: 100vh;
}
Способ 3: Абсолютное позиционирование
(если родитель имеет position: relative)
.parent {
position: relative;
height: 300px;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* сдвигает элемент назад на половину его размера */
}
div {
text-align: center; /* работает для текста, картинок, inline-элементов */
}
.parent {
text-align: center; /* для родителя */
}
.child {
display: inline-block; /* для дочернего элемента */
}
Горизонтально:
<div class="container">
<div class="box">Центрированный блок</div>
</div>
.container {
display: flex;
justify-content: center;
}
/* ИЛИ */
.box {
width: 200px;
margin: 0 auto;
}
По центру экрана (вертикально + горизонтально):
<div class="container">
<div class="box">По центру экрана</div>
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
margin: auto у элемента должна быть задана width.position: absolute родителю нужен position: relative.