Centered div with css

Выравниваем блок по центру страницы

Очень часто стоит задача выровнять блок по центру страницы / экрана, да ещё и так, чтобы без ява-скрипта, без задания жёстких размеров или отрицательных отступов, ещё чтобы и скроллбары работали у родителя, если блок превышает его размеры. В сети ходят достаточно много однообразных примеров как выровнять блок по центру экрана. Как правило большинство из них основаны на одних принципах.

Ниже представлены основные способы решения задачи, их плюсы и минусы. Чтобы понимать суть примеров, рекомендую уменьшить высоту / ширину окошка Result в примерах по указанным ссылкам.

Вариант 1. Отрицательный отступ.

Позиционируем блок атрибутами top и left на 50%, и заранее зная высоту и ширину блока, задаём отрицательный margin, который равен половине размера блока. Огромным минусом данного варианта является то, что нужно подсчитывать отрицательные отступы. Так же блок не совсем корректно ведёт себя в окружении скроллбаров — он попросту обрезается так как имеет отрицательные отступы.

Вариант 2. Автоматический отступ.

Менее распространённый, но схожий с первым. Для блока задаём ширину и высоту, позиционируем атрибутами top right bottom left на 0, и задаём margin auto. Плюсом данного варианта являются рабочие скроллбары у родителя, если у последнего задана 100% ширина и высота. Минусом данного способ является жёсткое задание размеров.

Вариант 3. Таблица.

Задаём родителю табличные стили, ячейке родителя устанавливаем выравнивание текста по центру. А блоку задаём модель строчного блока. Минусами мы получаем не рабочие скроллбары, и в целом не эстетичность «эмуляции» таблицы.

Чтобы добавить скролл в данный пример, придётся добавить в конструкцию ещё один элемент.
Пример: jsfiddle.net/serdidg/xkb615mu.

Вариант 4. Псевдо-элемент.

Данный вариант лишён всех проблем, перечисленных у предыдущих способов, а так же решает первоначально поставленные задачи. Суть состоит в том, чтобы у родителя задать стили псевдо-элементу before, а именно 100% высоту, выравнивание по центру и модель строчного блока. Так же само и у блока ставится модель строчного блока, выравнивание по центру. Чтобы блок не «падал» под псевдо-элемент, когда размеры первого больше чем родителя, указываем родителю white-space: nowrap и font-size: 0, после чего у блока отменяем эти стили следующими — white-space: normal. В данном примере font-size: 0 нужен для того, чтобы убрать образовавшийся пробел между родителем и блоком в связи с форматированием кода. Пробел можно убрать и иными способами, но лучшим считается просто его не допускать.

либо, если вам нужно, чтобы родитель занимал только высоту и ширину окна, а не всей страницы:

Вариант 5. Flexbox.

Одним из самых простых и элегантных способов является использования flexbox. Но имейте ввиду, что центральное позиционирование сохраняется даже если родительский блок меньше дочернего, последний будет выходить за рамки и обрезаться.

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

Вариант 6. Transform.

Подходит в случае если мы ограничены структурой, и нет возможности манипулировать родительским элементом, а блок выровнять как-то нужно. На помощь придёт css функция translate() . При значение 50% абсолютное позиционирование расположит верхний левый угол блока точно по центру, затем отрицательное значение translate сдвинет блок относительно своих собственных размеров. Учтите, что могут всплыть негативные эффекты в виде размытых граней или начертания шрифта. Также подобный способ может привести к проблемах с вычислением положения блока с помощью java-script’а. Иногда для компенсации потери 50% ширины из-за использования css свойства left может помочь заданное у блока правило: margin-right: -50%; .

Читайте также:  Java byte array to outputstream java

Вариант 7. Кнопка.

Пользователь azproduction предложил вариант, где блок обрамляется в тег button. Кнопка имеет свойство центрировать всё, что находится у неё внутри, а именно элементы строчной и блочно-строчной (inline-block) модели. На практике использовать не рекомендую.

Бонус

Используя идею 4-го варианта, можно задавать внешние отступы для блока, и при этом последний будет адекватно отображаться в окружении скроллбаров.
Пример: jsfiddle.net/serdidg/ugnp8ry7.

Так же можно выравнивать картинку по центру, и в случае если картинка больше родителя, масштабировать её по размеру родителя.
Пример: jsfiddle.net/serdidg/Lhpa1s70.
Пример с большой картинкой: jsfiddle.net/serdidg/tor2yudn.

Источник

Best way to center a on a page vertically and horizontally? [duplicate]

Best way to center a

element on a page both vertically and horizontally? I know that margin-left: auto; margin-right: auto; will center on the horizontal, but what is the best way to do it vertically, too?

Here’s a simple, clean and stable way to center divs in a container using only CSS. stackoverflow.com/a/31977476/3597276

30 Answers 30

The best and most flexible way

The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top and bottom (does not work in IE7).

##This trick will work with any sizes of div .

This is awesome. I have wondered for so long how to do this. I had tried it with top: 0; and left: 0;, but it seems that the addition of bottom: 0; and right: 0; make the difference. Thank you.

This solution only works if your element has a fixed height. See tombul’s answer for two solutions that do not change the element’s natural height.

Even though this did not work when the OP asked this question, I think, for modern browsers at least, the best solution is to use display: flex or pseudo classes.

You can see an example in the following fiddle. Here is the updated fiddle.

For pseudo classes an example could be:

.centerPseudo < display:inline-block; text-align:center; >.centerPseudo::before

The usage of display: flex, according to css-tricks and MDN is as follows:

There are other attributes available for flex, which are explained in above mentioned links, with further examples.

If you have to support older browsers, which don’t support css3, then you should probably use javascript or the fixed width/height solution shown in the other answers.

All browsers from 2012–2013 upwards support flex boxes. From today’s standpoint it should be safe enough to use it for new applications under most circumstances. The only situation I can think of where the older model should be preferred are business customers who rely on older infrastructure and can’t upgrade.

Simplicity of this technique is stunning:
(This method has its implications though, but if you only need to center element regardless of flow of the rest of the content, it’s just fine. Use with care)

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum accumsan tellus purus, et mollis nulla consectetur ac. Quisque id elit at diam convallis venenatis eget sed justo. Nunc egestas enim mauris, sit amet tempor risus ultricies in. Sed dignissim magna erat, vel laoreet tortor bibendum vitae. Ut porttitor tincidunt est imperdiet vestibulum. Vivamus id nibh tellus. Integer massa orci, gravida non imperdiet sed, consectetur ac quam. Nunc dignissim felis id tortor tincidunt, a eleifend nulla molestie. Phasellus eleifend leo purus, vel facilisis massa dignissim vitae. Pellentesque libero sapien, tincidunt ut lorem non, porta accumsan risus. Morbi tempus pharetra ex, vel luctus turpis tempus eu. Integer vitae sagittis massa, id gravida erat. Maecenas sed purus et magna tincidunt faucibus nec eget erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec mollis sem.

This will center element horizontally and vertically too. No negative margins, just power of transforms. Also we should already forget about IE8 shouldn’t we?

Читайте также:  Python как сделать число отрицательным

Yes, I used a lot this method. but, problem come if element is much higher then screen height (where height is unknown) . top of centered element would be cut. Even if element is putted in parent element where overflow is set to auto or scroll . Same problem using flex . Unfortunately, like last resort I use table to override this problem. Only when centered element will be much, much higher (dynamically populated).

Nelek — if parent element has fixed width and height you can add max-width:100% and max-height:100% to the image and prevent it from expanding the parent

Please check it in box model. its not coming on center. its showing as center but its exact pixel values are not there.

First position the div’s top left corner at the center of the page (using position: fixed; top: 50%; left: 50% ). Then, translate moves it up by 50% of the div’s height to center it vertically on the page. Finally, translate also moves the div to the right by 50% of it’s width to center it horizontally.

I actually think that this method is better than many of the others, since it does not require any changes on the parent element.

translate is better than translate3d in some scenarios due to it being supported by a greater number of browsers. https://caniuse.com/#feat=transforms2d

To sum it up, this method is supported on all versions of Chrome, Firefox 3.5+, Opera 11.5+, all versions of Safari, IE 9+, and Edge.

 
This div
is centered

Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.

Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.

Notice, however, that this method makes this div stay in one place while the page is being scrolled. This may be what you want but if not, there is another method.

Читайте также:  Centering div in html page

Now, if we try the same CSS, but with position set to absolute, it will be in the center of the last parent that has an absolute position.

 
This div
is centered

Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.

Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.

Источник

Оцените статью