Я пытаюсь горизонтально центрировать элемент блока <div>
на странице и установить минимальную ширину. Каков самый простой способ сделать это? Я хочу, чтобы элемент <div>
был встроен в остальную часть моей страницы. Я попытаюсь привести пример:
page text page text page text page text
page text page text page text page text
-------
| div |
-------
page text page text page text page text
page text page text page text page text
В случае нефиксированной ширины div (т.е. вы не знаете, сколько места займет div).
#wrapper {
background-color: green; /* for visualization purposes */
text-align: center;
}
#yourdiv {
background-color: red; /* for visualization purposes */
display: inline-block;
}
<div id="wrapper">
<div id="yourdiv">Your text</div>
</div>
Имейте в виду, что ширина #yourdiv
является динамической → она будет увеличиваться и уменьшаться, чтобы вместить текст внутри нее.
Вы можете проверить совместимость браузера на Caniuse
В большинстве браузеров это будет работать:
div.centre {
width: 200px;
display: block;
background-color: #eee;
margin-left: auto;
margin-right: auto;
}
<div class="centre">Some Text</div>
В IE6 вам нужно будет добавить еще один внешний div
:
div.layout {
text-align: center;
}
div.centre {
text-align: left;
width: 200px;
background-color: #eee;
display: block;
margin-left: auto;
margin-right: auto;
}
<div class="layout">
<div class="centre">Some Text</div>
</div>
width
. Если вы хотите, чтобы ширина элемента была динамической (в зависимости от его содержимого), посмотрите выбранный ответ.
Название вопроса и содержимого на самом деле другое, поэтому я опубликую два решения для этого, используя Flexbox
.
Я думаю, Flexbox
заменит/добавит текущее стандартное решение к моменту, когда IE8 и IE9 будут полностью уничтожены;)
Проверьте текущую таблицу совместимости браузера для flexbox
Одиночный элемент
.container {
display: flex;
justify-content: center;
}
<div class="container">
<img src="http://placehold.it/100x100">
</div>
Несколько элементов, но только центр
Поведение по умолчанию flex-direction: row
, которое выровняет все дочерние элементы в одной строке. Установка его на flex-direction: column
поможет уложить строки.
.container {
display: flex;
flex-direction: column;
}
.centered {
align-self: center;
}
<div class="container">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</p>
<div class="centered"><img src="http://placehold.it/100x100"></div>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>
</div>
CSS, HTML:
div.mydiv {width: 200px; margin: 0 auto}
<div class="mydiv">
I am in the middle
</div>
В вашей диаграмме также показан элемент уровня блока (обычно это div), а не встроенный.
В верхней части головы min-width
поддерживается в FF2 +/Safari3 +/IE7+. Может быть сделано для IE6 с использованием hackety CSS или простого бита JS.
Если старые браузеры не являются проблемой, используйте HTML5/CSS3. Если они есть, примените полисы и по-прежнему используйте HTML5/CSS3. Я предполагаю, что у вашего div нет полей или paddings здесь, но их относительно легко учесть. Код следует.
.centered {
position: relative;
left: 50%;
transform: translateX(-50%);
}
Что это такое:
div
относительно своего контейнера;div
на 50% от ширины контейнера горизонтально;div
собственную ширину.Легко представить этот процесс, чтобы подтвердить, что div
будет в конечном счете горизонтально центрироваться. В качестве бонуса вы можете центрировать вертикально без каких-либо дополнительных затрат:
.centered-vertically {
position: relative;
top: 50%;
transform: translateY(-50%);
}
Преимущество такого подхода заключается в том, что вам не нужно делать какие-либо противоречивые вещи, например, рассматривая ваш div как свой собственный вид, обертывая его в (часто семантически бесполезный) дополнительный контейнер или предоставляя ему фиксированную ширину, что не всегда возможно.
Не забывайте приставки префикса для transform
при необходимости.
.center {
margin-left: auto;
margin-right: auto;
}
Минимальная ширина не поддерживается глобально, но может быть реализована с использованием
.divclass {
min-width: 200px;
}
Затем вы можете установить свой div как
<div class="center divclass">stuff in here</div>
Вы должны использовать position: relative
и text-align: center
для родительского элемента, а затем display: inline-block
для дочернего элемента, который хотите центрировать. Это простой шаблон дизайна CSS, который будет работать во всех основных браузерах. Ниже приведен пример ниже или посмотрите Пример CodePen.
p {
text-align: left;
}
.container {
position: relative;
display: block;
text-align: center;
}
/* Style your object */
.object {
padding: 10px;
color: #ffffff;
background-color: #556270;
}
.centerthis {
display: inline-block;
}
<div class="container">
<p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius An Maius Septentrionarius Plas Inproportionabilit Constantinopolis Particularisticus.</p>
<span class="object centerthis">Something Centered</span>
<p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius.</p>
</div>
text-align: center
сделал свое дело. Просто нужно добавить это к родительскому элементу.
вы можете использовать margin: 0 auto
для своего css вместо margin-left: auto; margin-right: auto;
Пожалуйста, используйте приведенный ниже код, и ваш div будет в центре.
.class-name {
display:block;
margin:0 auto;
}
Если вы знаете ширину вашего div и он фиксирован, вы можете использовать следующую CSS:
margin-left: calc(50% - 'half-of-your-div-width');
где 'half-of-your-div-width' должна быть (очевидно) половиной ширины вашего div.
После девяти лет я думал, что пришло время принести новую версию. Вот мои два (и теперь один) фаворита.
Поле
Установите margin
на auto
. Вы должны знать, что последовательность направления является margin: *top* *right* *bottom* *left*;
или margin: *top&bottom* *left&right*
aside{
display: block;
width: 50px;
height: 100px;
background-color: green;
float: left;
}
article{
height: 100px;
margin: 0 0 0 50px; /* 50px aside width */
background-color: grey;
}
div{
margin: 0 auto;
display:block;
width: 60px;
height: 60px;
background-color: blue;
color: white;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<aside>
</aside>
<article>
<div>The div</div>
</article>
</body>
</html>
Центр: Уцененный, не используйте это!
Используйте теги <center></center>
чтобы обернуть вокруг <div></div>
.
Пример:
aside{
display:block;
background-color:green;
width: 50px;
height: 100px;
float: left;
}
center{
display:block;
background-color:grey;
height: 100px;
margin-left: 50px; /* Width of the aside */
}
div{
display:block;
width: 60px;
height: 60px;
background-color:blue;
color: white;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<aside>
</aside>
<article>
<center>
<div>The div</div>
</center>
</article>
</body>
</html>
Здесь я добавляю правильный ответ
Вы можете использовать этот код фрагмента и настроить. Здесь я использую 2 дочерних блока. Это должно показать центр страницы. Вы можете использовать один или несколько блоков.
<html>
<head>
<style>
#parent {
width: 100%;
border: solid 1px #aaa;
text-align: center;
font-size: 20px;
letter-spacing: 35px;
white-space: nowrap;
line-height: 12px;
overflow: hidden;
}
.child {
width: 100px;
height: 100px;
border: solid 1px #ccc;
display: inline-block;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="mydiv" id="parent">
<div class="child">
Block 1
</div>
<div class="child">
Block 2
</div>
</div>
</body>
</html>
Если ваш <div>
имеет position: absolute
, вам нужно использовать width: 100%;
#parent {
width: 100%;
text-align: center;
}
#child {
display: inline-block;
}
.center {
height: 20px;
background-color: blue;
}
.center>div {
margin: auto;
background-color: green;
width: 200px;
}
<div class="center">
<div>You text</div>
</div>
Добавьте этот класс в ваш файл css, он будет работать отлично шаги:
1) создайте этот первый
<div class="center-role-form">
<!--your div (contrent) place here-->
</div>
2) добавьте это в свой css
.center-role-form {
width: fit-content;
text-align: center;
margin: 1em auto;
}
Использование margin-left: auto и margin-right: авто может не работать в определенных ситуациях. Вот решение, которое всегда будет работать. Вы указываете требуемую ширину и задаете левый край до половины оставшейся ширины.
<div style="width:80%; margin-left:calc(10%);">
your_html
</div>
В вашем html файле вы пишете:
<div class="banner">
Center content
</div>
ваш файл css, который вы пишете:
.banner {
display: block;
margin: auto;
width: 100px;
height: 50px;
}
работает для меня.
Я использую теги div и span вместе с css-свойствами, такими как блок, кросс-браузерный встроенный блок и центр выравнивания текста, см. мой простой пример
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.block{display:block;}
.text-center{text-align:center;}
.border-dashed-black{border:1px dashed black;}
.inline-block{
display: -moz-inline-stack;
display: inline-block;
zoom: 1;
*display: inline;
}
.border-solid-black{border:1px solid black;}
.text-left{text-align:left;}
</style>
</head>
<body>
<div class="block text-center border-dashed-black">
<span class="block text-center">
<span class="block">
<!-- The Div we want to center set any width as long as it is not more than the container-->
<div class="inline-block text-left border-solid-black" style="width:450px !important;">
jjjjjk
</div>
</span>
</span>
</div>
</body>
</html>
Лучший ответ на этот вопрос - использовать margin-auto
, но для его использования вы должны знать width
своего div
в px
или %
.
Код CSS:
div{
width:30%;
margin-left:auto;
margin-right:auto;
}
margin-left:auto;
и margin-right:auto;
, вы можете написать margin: 0 auto;
Использование jQuery:
$(document).ready(function() {
$(".myElement").wrap( '<span class="myElement_container_new"></span>' ); // for IE6
$(".myElement_container_new").css({// for IE6
"display" : "block",
"position" : "relative",
"margin" : "0",
"padding" : "0",
"border" : "none",
"background-color" : "transparent",
"clear" : "both",
"text-align" : "center"
});
$(".myElement").css({
"display" : "block",
"position" : "relative",
"max-width" : "75%", // for example
"margin-left" : "auto",
"margin-right" : "auto",
"clear" : "both",
"text-align" : "left"
});
});
или, если вы хотите центрировать каждый элемент с классом ".myElement":
$(document).ready(function() {
$(".myElement").each(function() {
$(this).wrap( '<span class="myElement_container_new"></span>' ); // for IE6
$(".myElement_container_new").css({// for IE6
"display" : "block",
"position" : "relative",
"margin" : "0",
"padding" : "0",
"border" : "none",
"background-color" : "transparent",
"clear" : "both",
"text-align" : "center"
});
$(this).css({
"display" : "block",
"position" : "relative",
"max-width" : "75%",
"margin-left" : "auto",
"margin-right" : "auto",
"clear" : "both",
"text-align" : "left"
});
});
});
вы можете использовать позицию: relative; а затем установите левое и верхнее значения:
.cenverDiv{
position:relative;
left:30%;
top:0px;
}