Html выравнивание внутри блока

How do I vertically align text in a div?

I am trying to find the most effective way to align text with a div. I have tried a few things and none seem to work.

 
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

34 Answers 34

The correct way to do this in modern browsers is to use Flexbox.

See below for some older ways that work in older browsers.

For a CSS 2 browser, one can use display:table / display:table-cell to center content.

A sample is also available at JSFiddle:

 
everything is vertically centered in modern IE8+ and others.

It is possible to merge hacks for old browsers (Internet Explorer 6/7) into styles with using # to hide styles from newer browsers:

 
everything is vertically centered

It is quite ludicrous that tables are frowned upon as some kind of old-fashioned hack only a newbie would use, and here we are using «display:table-cell» in a DIV as a far hackier workaround.

Читайте также:  Java system path separator

@Desty I thought the same thing until I started working on accessibility. It wasn’t until I saw how screen readers do their thing that I started to accept this ‘new’ way of thinking.

@MarcelWilson I would have thought screen readers would find it easier to reason about simple tables. I know there’s the aria-. attributes that can help when using divs to simulate tables, but surely that’s like spraying air freshener on a dog turd instead of removing it.

You need to add the line-height attribute and that attribute must match the height of the div . In your case:

In fact, you could probably remove the height attribute altogether.

This only works for one line of text though, so be careful.

Here’s a great resource

Centering in CSS is a pain in the ass. There seems to be a gazillion ways to do it, depending on a variety of factors. This consolidates them and gives you the code you need for each situation.

Using Flexbox

Inline with keeping this post up to date with the latest tech, here’s a much easier way to center something using Flexbox. Flexbox isn’t supported in Internet Explorer 9 and lower.

Here are some great resources:

  • Some Text

  • A bit more text that goes on two lines

  • Even more text that demonstrates how lines can span multiple lines

Another solution

This method isn’t supported in Internet Explorer 8 and lower.

  • Some Text

  • A bit more text that goes on two lines

  • Even more text that demonstrates how lines can span multiple lines

Previous answer

A simple and cross-browser approach, useful as links in the marked answer are slightly outdated.

How to vertically and horizontally center text in both an unordered list and a div without resorting to JavaScript or CSS line heights. No matter how much text you have you won’t have to apply any special classes to specific lists or divs (the code is the same for each). This works on all major browsers including Internet Explorer 9, Internet Explorer 8, Internet Explorer 7, Internet Explorer 6, Firefox, Chrome, Opera and Safari. There are two special stylesheets (one for Internet Explorer 7 and another for Internet Explorer 6) to help them along due to their CSS limitations which modern browsers don’t have.

Andy Howard — How to vertically and horizontally center text in an unordered list or div

As I didn’t care much for Internet Explorer 7/6 for the last project I worked on, I used a slightly stripped down version (i.e. removed the stuff that made it work in Internet Explorer 7 and 6). It might be useful for somebody else.

.outerContainer < display: table; width: 100px; /* Width of parent */ height: 100px; /* Height of parent */ overflow: hidden; >.outerContainer .innerContainer < display: table-cell; vertical-align: middle; width: 100%; margin: 0 auto; text-align: center; >li

Источник

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

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

На этом уроке, вы узнаете несколько способов выравнивания по центру блока внутри блока по вертикали и горизонтали. В качестве блоков могут быть любые фигуры.

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

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

Выравнивание блока внутри блока.

Общие стили для всех способов:

Зададим позицию блока относительной по отношению к окну браузера. Это в дальнейшем даст возможность блоку-дочке задать абсолютное позиционирование уже к блоку-родителю.

.block width: 250px;
height: 300px;
background-color: red;
position: relative;

Исходные размеры картинки-иконки такие же, как и ширина красного прямоугольника, уменьшим её максимальные размеры.

.icon max-width: 60%;
max-height: 60%;
>

HTML-разметка у всех способов одинаковая, отличаться будут только стили.

Способ первый

Html выравнивание внутри блока

Положение изображения автоматически определяет сам браузер с помощью свойства margin: auto.

.first position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1;
margin: auto;
>

Способ второй

Html выравнивание внутри блока

Этот способ выравнивания по центру никогда еще не подводил. Вы спросите, зачем нужно последнее свойство transform? Если убрать transform, то иконка не будет стоять точно по центру, поскольку не учитываются её собственные размеры. Центр иконки не совпадает с центром блока-родителя. Мы двигаем иконку назад и вниз на половину её собственного размера.

.second position: absolute;
top: 50%;
left: 50%;
z-index: 1;
transform: translate(-50%, -50%);
>

Способ третий

Отличается от двух предыдущих тем, что класс flex задан блоку div, а не картинке.

Html выравнивание внутри блока

.flex display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
>

А что будет, если после тега img, всем трем блокам добавить текст?

Html выравнивание внутри блока

Ольга Смирнова

Консультант по кредитам

У первых двух способов, параграфы с текстом окажутся наверху, несмотря на то, что в HTML-коде, они стоят после изображения. Для перемещения текста под картинку, потребуется обернуть теги img, h2 и p в ещё один блок div и прописать ему свойство text-align: center.

Выравнивание блока внутри блока.

Однако с третьим способом выравнивания на флексах, не возникает таких проблем, конструкция не нуждается в дополнительном оберточном блоке. Параграфы с текстом встают точно посередине и после изображения и там где надо.

Выравнивание блока внутри блока.

Заключение

Лишний раз можно убедиться в продвинутости и удобстве верстки на флексах. Советую всем тем верстальщикам, кто еще не верстает на флексах, наконец-то начать использовать флексы. Оправдание, почему вы не верстаете на флексах, может быть только одно – экзотическое желание заказчика, угодить пользователям «древних» браузеров. В остальных же случаях, нет ни одной причины почему не нужно верстать на флексах.

Если вы не знаете с чего начать уже зарабатывать свои первые деньги, то лучшим вариантом будет — научиться верстать лендинги, с помощью этого видеокурса «О создании лендинга под ключ».

Создано 20.02.2019 10:00:20

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Выравнивание элементов внутри div

    Тема наверняка избитая, но остаются непонятки. Пытаюсь сверстать окошко div-ами. Получился вот такой код:

       div#popup_container < width: 240px; height: 150px; left: 359px; top: 206px; background-color:#e2d5e9 >div#popup_left < width:9px; height:150px; float:left; left:3px >div#popup < float:left; >div#popup_right < width:12px; height:150px; float:right; >img#img_big < width:200px; margin-left:10px; margin-top:10px; height:130px; >.arrow  

    Вопрос такой: почему для объекта класса arrow нельзя никак задать отступ, кроме как margin? Какие-нибудь padding-top и top принимают значение auto, даже если их задать явно. popup-left тоже нельзя сдвинуть.

    4 ответа 4

    Все блочные элементы имеют отступы margin и padding. Например, тут желтый фон — это margin, а красный — это padding. Однако, в режиме разметки strict img могут быть рендерится как inline элементы, по этому часто для всех img явно задают свойство display: block;

    Для того, что бы позиционировать элементы относительно текущего местоположения при помощи свойств top , bottom , etc, необходимо выставить свойство position: relative; К примеру, что бы отцентрировать по вертикали элементы с классом arrow, можно задать стиль:

    Я не очень понял вопроса, но можно задать свойство у popup_left и popup_right

    Источник

    How can I center text (horizontally and vertically) inside a div block?

    I have a div set to display:block ( 90px height and width ), and I have some text inside. I need the text to be aligned in the center both vertically and horizontally. I have tried text-align:center , but it doesn’t do the vertical centering part, so I tried vertical-align:middle , but it didn’t work. Any ideas?

    I finally found a solution that works with relative sizes and no fixed heights: stackoverflow.com/a/16195362/1301331

    It is very important to know how to center / middle elements. The below document has given a very clear picture. w3.org/Style/Examples/007/center.en.html

    Here are two simple methods to center objects within divs, vertically, horizontally or both (pure CSS): stackoverflow.com/a/31977476/3597276

    27 Answers 27

    If it is one line of text and/or image, then it is easy to do. Just use:

    text-align: center; vertical-align: middle; line-height: 90px; /* The same as your div height */ 

    That’s it. If it can be multiple lines, then it is somewhat more complicated. But there are solutions on http://pmob.co.uk/. Look for «vertical align».

    Since they tend to be hacks or adding complicated divs. I usually use a table with a single cell to do it. to make it as simple as possible.

    Update for 2020:

    Unless you need make it work on earlier browsers such as Internet Explorer 10, you can use flexbox. It is widely supported by all current major browsers. Basically, the container needs to be specified as a flex container, together with centering along its main and cross axis:

    To specify a fixed width for the child, which is called a «flex item»:

    To shrink-wrap the content, it is even simpler: just remove the flex: . line from the flex item, and it is automatically shrink-wrapped.

    The examples above have been tested on major browsers including MS Edge and Internet Explorer 11.

    One technical note if you need to customize it: inside of the flex item, since this flex item is not a flex container itself, the old non-flexbox way of CSS works as expected. However, if you add an additional flex item to the current flex container, the two flex items will be horizontally placed. To make them vertically placed, add the flex-direction: column; to the flex container. This is how it works between a flex container and its immediate child elements.

    There is an alternative method of doing the centering: by not specifying center for the distribution on the main and cross axis for the flex container, but instead specify margin: auto on the flex item to take up all extra space in all four directions, and the evenly distributed margins will make the flex item centered in all directions. This works except when there are multiple flex items. Also, this technique works on MS Edge but not on Internet Explorer 11.

    Update for 2016 / 2017:

    It can be more commonly done with transform , and it works well even in older browsers such as Internet Explorer 10 and Internet Explorer 11. It can support multiple lines of text:

    position: relative; top: 50%; transform: translateY(-50%); 

    To shrink-wrap the width:

    The solution above used a fixed width for the content area. To use a shrink-wrapped width, use

    position: relative; float: left; top: 50%; left: 50%; transform: translate(-50%, -50%); 

    If the support for Internet Explorer 10 is needed, then flexbox won’t work and the method above and the line-height method would work. Otherwise, flexbox would do the job.

    Источник

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