Css выровнять div внутри div

Как выровнять блок по центру — полное руководство по центрированию DIV-элемента

Сегодняшняя статья направлена на то, чтобы показать, как при помощи нескольких CSS-трюков выровнять div по центру, как по горизонтали, так и по вертикали. Также мы расскажем, как произвести центрирование по всей странице либо в отдельно взятом div-элементе .

Простое центрирование DIV-элемента на странице

Этот метод будет отлично работать во всех браузерах.

Значение auto в свойстве margin устанавливает левый и правый отступ на все пространство, доступное на странице. Здесь важно запомнить, что у центрируемого div-элемента обязательно должно быть установлено значение width .

Центрируем DIV внутри DIV-элемента старым способом

Этот метод div выравнивания по центру будет работать во всех браузерах.

Внешний div может быть помещен как угодно, но у внутреннего блока div обязательно должна быть указана ширина ( width ).

Центрируем DIV внутри DIV-элемента с помощью inline-block

В этом методе центрирования div внутри div необязательно указывать ширину внутреннего элемента. Он будет работать во всех современных браузерах, включая IE8 .

Читайте также:  Hardest way to learn python

Свойство text-align работает только в inline-элементах . Значение inline-block позволяет отобразить внутренний div в качестве inline-элемента , а также в качестве блока ( inline-block ). Свойство text-align во внешнем div-элементе позволит нам центрировать внутренний div .

Центрируем DIV внутри DIV-элемента горизонтально и вертикально

Здесь для центрирования div по центру страницы используется margin: auto . Пример будет работать во всех современных браузерах.

У внутреннего div-элемента должна быть указана ширина ( width ) и высота ( height ). Метод не сработает, если у внешнего div-элемента будет фиксированная высота.

Центрируем DIV по нижней границе страницы

Здесь для расположения div по центру по вертикали используется margin: auto и абсолютное позиционирование для внешнего элемента. Метод будет работать во всех современных браузерах.

У внутреннего div должна быть установлена ширина. Пространство внизу страницы регулируется с помощью свойства bottom внешнего div . Вы также можете центрировать div по верхней границе страницы, заменив свойство bottom на свойство top .

Центрируем DIV на странице вертикально и горизонтально

Здесь, чтобы выровнять div по центру, снова используется margin: auto и абсолютное позиционирование внешнего div . Метод будет работать во всех современных браузерах.

У div-элемента должна быть установлена ширина ( width ) и высота ( height ).

Делаем адаптивное центрирование DIV-элемента на странице

Здесь для выравнивания div по центру средствами CSS мы делаем ширину div-элемента адаптивной, чтобы она реагировала на изменения размеров окна. Этот метод работает во всех браузерах.

У центрированного div-элемента должно быть установлено свойство max-width .

Центрируем DIV внутри элемента с помощью свойств внутреннего блока

Внутренний div-элемент здесь адаптивен. Этот метод расположения div внутри div по центру будет работать во всех браузерах.

У внутреннего div должно быть установлено свойство max-width .

Центрируем два адаптивных div-элемента рядом друг с другом

Здесь у нас два расположенных рядом адаптивных div-элемента. Этот метод установки div по центру экрана будет работать во всех современных браузерах.

.container < text-align: center; >.left-div < display: inline-block; max-width: 300px; vertical-align: top; >.right-div < display: inline-block; max-width: 150px; >screen and (max-width: 600px) < .left-div, .right-div < lef max-width: 100%; >>

Здесь у нас несколько элементов с примененным свойством inline-block , расположенных внутри центрированного контейнера. В этом примере также используются медиа-запросы CSS ; то есть, если размер экрана меньше 600 пикселей, то свойство max-width как для левого, так и для правого div-элемента устанавливается на 100%.

DIV-элемент, центрированный при помощи Flexbox

Здесь мы располагаем CSS div по центру с помощью Flexbox . Он предназначен для того, чтобы облегчить процесс разработки дизайна пользовательских интерфейсов. Этот модуль поддерживается Chrome 38+ , IE11 , Microsoft Edge , Firefox 38+ , Safari 9+ , Opera 30+ , iOS Safari 9+ , а также Android Browser 40+ .

Значение свойства height может быть любым, но только больше размера центрированного div-элемента.

Валентин Сейидов автор-переводчик статьи « THE COMPLETE GUIDE TO CENTERING A DIV »

Источник

How can I horizontally center an element?

Of those great answers, I just want to highlight that you must give «#inner» a «width», or it will be «100%», and you can’t tell if it’s already centered.

display:flex; is the easiest to remember (Chrome gives you guides in DevTools) and supports centering on both axes.

130 Answers 130

With flexbox it is very easy to style the div horizontally and vertically centered.

To align the div vertically centered, use the property align-items: center .

Other Solutions

You can apply this CSS to the inner :

Of course, you don’t have to set the width to 50% . Any width less than the containing will work. The margin: 0 auto is what does the actual centering.

If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:

It will make the inner element center horizontally and it works without setting a specific width .

You also set the top and bottom margins to 0, which is unrelated. Better putting margin-left: auto; margin-right: auto I think.

To support mobile browsers, I do not recommend using width: 50% . Use something like max-width: 300px instead.

voted most but not a better solution. the best way to do this is to use the combination of div and span tag, block css property and cross browser inline-block, and text center will do the simple magin

If you don’t want to set a fixed width on the inner div you could do something like this:

That makes the inner div into an inline element that can be centered with text-align .

@SabaAhang the correct syntax for that would be float: none; and is probably only needed because #inner has inherited a float of either left or right from somewhere else in your CSS.

This is a nice solution. Just keep in mind that inner will inherit text-align so you may want to set inner’s text-align to initial or some other value.

The best approaches are with CSS3.

The old box model (deprecated)

display: box and its properties box-pack , box-align , box-orient , box-direction etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.

According to your usability you may also use the box-orient, box-flex, box-direction properties.

The modern box model with Flexbox

Read more about centering the child elements

And this explains why the box model is the best approach:

Safari, as of now, still requires -webkit flags for flexbox ( display: -webkit-flex; and -webkit-align-items: center; and -webkit-justify-content: center; )

I always think that use lots code is bad practice for example with this code I center my div: display: table; margin: auto; simple and easy

Make sure the parent element is positioned, i.e., relative, fixed, absolute, or sticky.

If you don’t know the width of your div, you can use transform:translateX(-50%); instead of the negative margin.

With CSS calc(), the code can get even simpler:

The principle is still the same; put the item in the middle and compensate for the width.

I don’t like this solution because when the inner element is too broad for the screen, you can’t scroll over the whole element horizontally. margin: 0 auto works better.

The default width for most block level elements is auto, which fills the available area on screen. Just being centered places it in the same position as left alignment. If you wish it to be visually centered you should set a width (or a max-width although Internet Explorer 6 and earlier do not support this, and IE 7 only supports it in standards mode).

I’ve created this example to show how to vertically and horizontally align .

The code is basically this:

And it will stay in the center even when you resize your screen.

+1 for this method, I was about to answer with it. Note that you must declare a width on the element you wish to center horizontally (or height if centering vertically). Here’s a comprehensive explanation: codepen.io/shshaw/full/gEiDt. One of the more versatile and widely-supported methods of centering elements vertically and/or horizontally.

You cannot use padding within the div, but if you want to give the illusion use a border of the same color.

Some posters have mentioned the CSS 3 way to center using display:box .

This syntax is outdated and shouldn’t be used anymore. [See also this post].

So just for completeness here is the latest way to center in CSS 3 using the Flexible Box Layout Module.

So if you have simple markup like:

. and you want to center your items within the box, here’s what you need on the parent element (.box):

.box < display: flex; flex-wrap: wrap; /* Optional. only if you want the items to wrap */ justify-content: center; /* For horizontal alignment */ align-items: center; /* For vertical alignment */ >* < margin: 0; padding: 0; >html, body < height: 100%; >.box < height: 200px; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; border: 2px solid tomato; >.box div < margin: 0 10px; width: 100px; >.item1 < height: 50px; background: pink; >.item2 < background: brown; height: 100px; >.item3

If you need to support older browsers which use older syntax for flexbox here’s a good place to look.

The Flexbox specification has gone through 3 major revisions. The most recent draft is from Sept 2012, which officially deprecates all previous drafts. However, browser support is spotty (particularly old Android browsers): stackoverflow.com/questions/15662578/…

Isn’t the «justify-content: center;» for the vertical alignment and the «align-items: center;» for the horizontal alignment?

@WouterVanherck it depends on the flex-direction value. If it is ‘row’ (the default) — then justify-content: center; is for the horizontal alignment (like I mentioned in the answer) If it is ‘column’ — then justify-content: center; is for the vertical alignment.

If you don’t want to set a fixed width and don’t want the extra margin, add display: inline-block to your element.

Centering a div of unknown height and width

Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera, etc.)

This works with any content

Tinker with it further on Codepen or on JSBin.

This is the only one that works for perfect centering and will remain centered even after the contents in the div are modified.

It’s a nice trick, but there is a little caveat. If the element has inline content that’s wider than 50% of the parent’s width, then the extra 50% offset from the left will extrapolate the parent’s width, breaking the content to the next lines to avoid overflow. But it’s possible to keep the content inline by setting in the centered element the white-space attribute to nowrap . Try that in this JSFiddle.

Set the width and set margin-left and margin-right to auto . That’s for horizontal only, though. If you want both ways, you’d just do it both ways. Don’t be afraid to experiment; it’s not like you’ll break anything.

It cannot be centered if you don’t give it a width. Otherwise, it will take, by default, the whole horizontal space.

The way I usually do it is using absolute position:

The outer div doesn’t need any extra properties for this to work.

I recently had to center a «hidden» div (i.e., display:none; ) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery code to display the hidden div and then update the CSS content to the automatic generated width of the table and change the margin to center it. (The display toggle is triggered by clicking on a link, but this code wasn’t necessary to display.)

NOTE: I’m sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don’t have any width and can’t be resized/centered until after they are displayed.

For Internet Explorer, Firefox, and Chrome:

The text-align: property is optional for modern browsers, but it is necessary in Internet Explorer Quirks Mode for legacy browsers support.

Источник

How can I center a div within another div? [duplicate]

I suppose that the #container will be centered within #main_content . However, it is not. Why isn’t this working, and how can I fix it?

what browsers are you testing on? Here’s a fiddle with your code and it’s working fine on the latest chrome : jsfiddle.net/mFwCp

27 Answers 27

You need to set the width of the container ( auto won’t work):

The CSS reference by MDN explains it all.

Technically, your inner DIV ( #container ) is centered horizontally. The reason you can’t tell is because with the CSS width: auto property the inner DIV is expanding to the same width as its parent.

In this example, I simply set the width of #container to 50px and set the background to red so that you can see that it is centered.

I think the real question is «How do I center elements horizontally with CSS?» and the answer is (drum roll please): it depends!

I won’t do a full rehash of the myriad ways to center things with CSS when W3Schools does it so nicely here: http://www.w3schools.com/css/css_align.asp but the basic idea is that for block level elements you simply specify the desired width and set the left and right margins to auto .

Please note: This answer only applies to block level elements! To position an inline element, you will need to use the text-align: center property on the first block parent.

Источник

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