How to center text css
How to center text css
How to Vertically Center Text with CSS
Centering elements vertically with CSS often gives trouble. However, there are several ways of vertical centering, and each is easy to use.
Use the CSS vertical-align property
The vertical-align property is used to vertically center inline elements.
The values of the vertical-align property align the element relative to its parent element:
Example of vertically aligning a text:
Result
Use CSS Flexbox
With Flexbox, it is possible to align elements vertically (or horizontally) with the align-items, align-self, and justify-content properties.
Example of vertically aligning a text with Flexbox:
Use the CSS display property
With the display property, we’re going to set the elements to «table» and «table cell». We center the content with the vertical-align property.
Example of vertically aligning a text with the CSS display property:
Use the CSS line-height property
Add the line-height property to the element containing a text larger than its font size. By default, equal spaces will be added above and below the text, and you’ll get a vertically centered text.
Example of vertically aligning a text with the CSS line-height property:
The following example works for a text with single and multiple lines. However, it requires a fixed height container.
Example of vertically aligning a text by using the CSS line-height property with a fixed height container:
Set equal top and bottom padding
When vertically aligning a text with the padding property, we must set the top and bottom padding of the parent element to be equal.
Example of vertically aligning a text with the CSS padding property:
When setting the padding, use % to help them grow dynamically. This method requires some calculations to understand what values are needed on the top and bottom, so as they can grow dynamically. If you set the height to «relative», the calculation will not be needed.
Set absolute positioning and negative margin
We can vertically align a text with the CSS position and margin properties used with block-level elements. Do not forget to set the height of the element that you want to center.
Example of vertically aligning a text with the CSS position and margin properties:
Set absolute positioning and stretching
By setting absolute positioning and stretching, we instruct the browser to automatically set the margins of the child element so as they become equal.
Example of vertically aligning a text with the CSS position property:
Set the CSS transform property
Example of vertically aligning a text with the CSS transform property:
Use floater div
Using the floater div method requires to have an empty
How to Center Text in CSS
Written by Anna Fitzgerald
Learn more tips with this introductory CSS guide for marketers.
Aligning text along the center axis can make a page look organized and symmetrical — it can also draw the visitor’s eye to particular elements on the page. For example, titles, block quotes, and call-to-actions are often centered to disrupt the flow of the document and grab the reader’s attention. That’s why the text CTA below is centered.
To ensure you understand this common alignment type, we’ll walk through how to center text horizontally first. Then we’ll look at a few ways of centering text vertically.
How to Center Text in CSS
To center text in CSS, use the text-align property and define it with the value “center.”
Let’s start with an easy example. Say you have a text-only web page and want to center all the text. Then you could use the CSS universal selector (*) or the type selector body to target every element on the page. Then you’d set the text-align property to center.
Your CSS might also look like this:
Here’s the result:
An Introductory Guide to CSS for Marketers
Fill out the form for your copy of this CSS 101 guide.
What if you don’t want all the text on the page to be centered, or your page contains images and other elements besides text? In that case, you’d use the same text-align property but a different CSS selector. For example, say you want the headings centered on a page, but the paragraphs to be left aligned. Then you’d use the type selector h2 and set the text-align property to center. You don’t have to add any more code to align the paragraphs — by default, they’ll be left aligned.
Here’s the result:
If you’d like to center only a single element on the page, then you can add an id attribute to the element and target it with an ID selector. Or, you could use inline CSS.
First, let’s use an ID attribute and selector.
Here’s the result:
Now let’s use inline CSS. But instead of centering headings and paragraphs, let’s center text inside another element.
Say I’m building a web page using Bootstrap CSS and I add a Bootstrap button that I want to center on the page. Aligning the button, and the text inside the button, would differ slightly from the examples above. That’s because the text-align property only works on block-level elements like headings and paragraphs, not inline elements like buttons.
So, first, I’d have to wrap the button in a div. Then I could apply the inline CSS to the div as shown below.
Here’s the HTML with inline CSS:
Here’s the result:
As you can tell from the examples above, the text-align property only specifies the horizontal alignment of text. Specifying the vertical alignment of text is more complicated. Let’s take a look below.
Vertically Align Text
You can center text vertically in a number of ways. For the methods below, the text will have to be contained by a parent element, like a div. Let’s start with the easiest.
Note that if you want your text to also be horizontally centered, simply add the text-align property set to center to the CSS of any of the examples below.
Vertically Center Text Using CSS Padding
One of the simplest solutions to vertically center text is to use top and bottom padding.
To apply CSS padding to an element, I can use the long form method and define both the padding-top and padding-bottom properties in my CSS. Or I can use the shorthand padding property and include three values: the first value will represent the top padding, the second will represent the left and right padding, and the third will represent the bottom padding.
Here’s the CSS using the shorthand method:
Here’s the result:
Vertically Center Text Using the CSS Line-Height Property
To vertically center text within an element, you can also use the CSS line-height property. You’ll have to set the property with a value that is equal to the container element’s height.
Here’s the result:
Vertically Center Text Using the CSS Position and Transform Properties
Another method for centering text vertically on a page requires the CSS position property and the transform property.
To start, set the position of the div containing the text to relative. Then you want to style the paragraph within the div. First, set its position to absolute so that it’s taken out of the normal document flow. Then set the left and top properties to 50%. This tells the browser to line up the left and top edge of the paragraph with the center of the page horizontally and vertically (ie. 50% to the right and down the page). The problem is we don’t want the edges of the paragraph to be lined up in the middle of the page — we want the center of the paragraph to be lined up in the middle of the page.
That’s where the CSS transform property comes in. Using the transformation method known as the translate() method, we can move the paragraph along the X- and the Y-axis. To truly center the paragraph, we want to move it 50% to the left and up from its current position. That will tell the browser to put the center of the paragraph in the center of the page.
Here’s the result:
Vertically Center Text Using Flexbox
Flexbox is one of the best methods for vertically (and horizontally) centering text since it’s responsive and doesn’t require margin calculations.
First, you need to define the parent container — in this case, the div — as a flex container. You do this by setting the display property to “flex.” Then, define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
Here’s the result:
Centering Text on your Website
If you have some basic knowledge of HTML and CSS, you can easily center text on your web pages. This can help you build custom page layouts and make your content stand out. If you’re interested in other alignment types, check out How to Left, Right & Center Align Text in HTML.
Originally published Nov 9, 2020 7:00:00 AM, updated August 12 2022
Centering in CSS: A Complete Guide
Centering things in CSS is the poster child of CSS complaining. Why does it have to be so hard? They jeer. I think the issue isn’t that it’s difficult to do, but in that there so many different ways of doing it, depending on the situation, it’s hard to know which to reach for.
So let’s make it a decision tree and hopefully make it easier.
I need to center…
You can center inline elements horizontally, within a block-level parent element, with just:
This will work for inline, inline-block, inline-table, inline-flex, etc.
Is it a block level element?
This will work no matter what the width of the block level element you’re centering, or the parent.
Note that you can’t float an element to the center. There is a trick though.
Is there more than one block level element?
If you have two or more block-level elements that need to be centered horizontally in a row, chances are you’d be better served making them a different display type. Here’s an example of making them inline-block and an example of flexbox:
Unless you mean you have multiple block level elements stacked on top of each other, in which case the auto margin technique is still fine:
Vertical centering is a bit trickier in CSS.
Is it inline or inline-* elements (like text or links)? Is it a single line?
Sometimes inline / text elements can appear vertically centered, just because there is equal padding above and below them.
If padding isn’t an option for some reason, and you’re trying to center some text that you know will not wrap, there is a trick were making the line-height equal to the height will center the text.
Equal padding on top and bottom can give the centered effect for multiple lines of text too, but if that isn’t going to work, perhaps the element the text is in can be a table cell, either literally or made to behave like one with CSS. The vertical-align property handles this, in this case, unlike what it normally does which is handle the alignment of elements aligned on a row. (More on that.)
If something table-like is out, perhaps you could use flexbox? A single flex-child can be made to center in a flex-parent pretty easily.
Remember that it’s only really relevant if the parent container has a fixed height (px, %, etc), which is why the container here has a height.
If both of these techniques are out, you could employ the “ghost element” technique, in which a full-height pseudo-element is placed inside the container and the text is vertically aligned with that.
It’s fairly common to not know the height in web page layout, for lots of reasons: if the width changes, text reflow can change the height. Variance in the styling of text can change the height. Variance in the amount of text can change the height. Elements with a fixed aspect ratio, like images, can change height when resized. Etc.
But if you do know the height, you can center vertically like:
It’s still possible to center it by nudging it up half of it’s height after bumping it down halfway:
If you don’t, you just need the content inside vertically centered, using tables or CSS display to make elements into tables can do the trick.
No big surprise, this is a lot easier in flexbox.
You can also get centering in flexbox using margin: auto; on the child element.
Both Horizontally & Vertically
You can combine the techniques above in any fashion to get perfectly centered elements. But I find this generally falls into three camps:
Is the element of fixed width and height?
Using negative margins equal to half of that width and height, after you’ve absolutely positioned it at 50% / 50% will center it with great cross-browser support:
If you don’t know the width or height, you can use the transform property and a negative translate of 50% in both directions (it is based on the current width/height of the element) to center:
To center in both directions with flexbox, you need to use two centering properties:
This is just a little trick (sent in by Lance Janssen) that will pretty much work for one element:
You can totally center things in CSS.
Comments
Good idea! I like the concept of this article and also the show/hide structure. I applaud you, sir.
However, I think you’re missing the spirit behind the classic “centering is hard” complaint in a couple of places, which, at least for me, always comes back to not knowing the height of the elements.
1) Your display: table-cell fix relies on knowing the height of the child element.
3) In your “both hor & vert example” where the height is unknown, it’s a little weird to have the child be pos: absolute and imply that this is no big deal. I think pos: absolute is a major caveat when laying things out, since it can have the unintended consequence of having elements layer over one another.
4) Also, in that same pen, the element fails to stay vertically centered if it has a sibling that stretches the vertical height of the parent.
Regardless, I still really like the idea of this –it’s sorely needed. I just think it would be improved if you acknowledged some of the caveats that I think are at the root of the complaint you’re trying to dismiss.
1) It doesn’t actually. I updated the example to put the height on the table instead.
2) Vertical centering is only relevant if the parent has a set height. If the parent doesn’t have a set height, what are you centering within? Even if the answer is “the entire page”, then you need to set the height of (probably) both html, body
3) That’s fair. It’s just one example. In my experience, if you’re trying to center something both ways like that, it’s probably a modal, in which the absolute (or fixed) positioning is going to be used. If it’s not, you can combine any of the other techniques as needed. And there is always flexbox which I covered a bunch.
4) Demo me on this one? I’m having a hard time picturing/reproducing.
Hey Chris! Thanks for the reply.
Re #1: I feel like we’re missing each other on this one. The first thing I did when I looked at the pen was delete the HTML table, since that’s not realistic/preferred for most of my use cases, though maybe I am being overly table-phobic there. Regardless, that leaves the div html, which indeed does have an explicit height, which is what is powering the vertical centering. Result: http://codepen.io/anon/pen/xIvqh
Re #2: I actually am on the same track here as the commenter you just buried for tone. Let’s say I want to vertically center two inline-block siblings of different height: http://codepen.io/anon/pen/Cjdeo
Sorry, I am kind of misinterpreted, misrepresenting what you are doing with #1. Truce there, as well.
HTML Center Text – How to CSS Vertical Align a Div
In the HTML and CSS world, it’s all about the layout structure and the distribution of elements. We usually use HTML to define the markup and structure, while CSS helps us handle the styling and alignment of elements.
In this post we are going to learn a little bit about the different ways we can center HTML elements and handle vertical alignment with CSS.
First we going to learn how to align text with CSS.
Next, we will cover how to align a div and any other elements.
And finally we will learn how we can put text and a div together within a container.
How to center text
There are many way to center text using CSS.
Using the Float property
Float is an easy way to align text.
You can learn more about the uses of Float here.
Using Text-align
text-align is a more convenient and more specific way to align text. It allows us to place the text at the center or to the left or right side, as the following example shows:
How to align a div
Well, there are a plenty of ways to do that.
The same way we use Float to align text, we can use it to align a div element as well.
Well, these two methods provide very modern ways to align and work with your layout in CSS. Let’s look at Flexbox in more in detail.
Flexbox
Flexbox offers an easy and straightforward way to align a div – and it’s my favorite method so far to handle layouts in CSS (I use it everyday).
Let’s look at what we’d do with Flexbox to see how it works by recreating the same example as above.
let’s break it down
The example above applies to all elements’ children as a group.
Imagine if we wanted to align a single div inside the container. We can always use align-self to align a single element.
We can apply the same thing to a text with Flexbox as in the following example:
This is a great tweet by Julia Evans which illustrates centering in CSS in general:
Original Tweet here
Wrap up
There are many way to center elements in CSS. And you will always learn new things over time as you practice more and more.
So I recommend that you work through some examples from what you learned today so it sticks.
Frontend Developer, Technical Writer, Bootcamp Instructor ➡️ Join my React/React Native class at nucamp.co and change your career in 6 months, use code F3748T ➡️ Get in touch info.said.dev@gmail.com
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
Вертикальное и горизонтальное центрирование всего и вся в CSS Flexbox
В этой статье будет рассмотрен очень важный момент при вёрстке любого шаблона, а именно центрирование элементов. В Flexbox это стало гораздо проще и стабильнее.
Эта статья одна из завершающих из цикла переводов про CSS Flexbox. Скоро все они будут скомпонованы в один большой, понятный и объёмный гайд по изучению CSS Flexbox.
👉 Мой Твиттер — там много из мира фронтенда, да и вообще поговорим🖖. Подписывайтесь, будет интересно: ) ✈️
В примерах с навигацией используется пример кода отсюда.
Разочаровались в попытках использования CSS для выравнивания по центру с div ’ами, изображениями и текстом?
Вообще, выравнивание горизонтально и вертикально в CSS всегда было таким, каким-то странным и зачастую не таким, как вообще задумывалось. Я успел применить буквально все хаки в этом направлении за последние несколько лет.
CSS Flexbox исправил эти недочеты. Теперь у вас больше контроля над выравниванием HTML элементов, включая опцию идеального центрирования буквально всего, что только можно.
Вообще, во Flexbox стало очень легко отцентровывать текст, изображения и div ’ы. Но это не означает того, что это единственный способ центрировать контент.
Вы наверное делали как я и искали на пространствах сети лучшие способы горизонтальной и вертикальной центровки в HTML.
Я не буду докучать вам объяснениями этих старых хаков с применением внешних отступов, абсолютного и фиксированного позиционирования. Они до сих пор работают, но уже сейчас пора от них избавляться.
Как отцентровать текст в CSS с помощью text-align
Выставление text-align на center является самым распространенным способом горизонтального выравнивания текста с помощью CSS. Этот подход не ограничивается только текстом, он может использоваться для центровки почти всех элементов потомков, которые меньше родительского контейнера.
Текст или элемент центрирования должен быть обёрнут или находится в родительском элементе, который самой собой шире.
Если у вас несколько дочерних элементов, то они все дружно будут отцентрированы внутри родительского контейнера.
text-align имеет несколько свойств:
center : текст отцентрован.
left : текст выровнен по левой стороне контейнера.
right : текст выровнен по правой стороне контейнера.
justify : текст выстраивается ровно по левой и правой граням контейнера, за исключением последней строки.
justify-all : выравнивает последнюю строку.
end : start, только наоборот.
Используйте эти свойства для выравнивания текста внутри родительского элемента или div ’а врапера. Тут всё обыденно и просто.
Выравниваем элементы горизонтально с text-align
Хороший пример — центровка панели навигации. Это может показаться тягомотиной, так как ширина каждого элемента меню зависит от его текста.
Вообще, центрирование куда проще, если вы знаете точную ширину родителя и его потомков.
И теперь у вас горизонтально выровненное меню.
Это хороший способ для центрирования элементов, но это очень старый хак.
В наше время у нас уже есть кое-что получше, а именно CSS Flexbox.
CSS Flexbox
Flexbox был добавлен в стандарты CSS несколько лет назад, в основном для того, чтобы разобраться с распределением места и выравниванием элементов. По сути, это синтаксис одномерной раскладки.
А в купе с более новым CSS Grid, веб-разработчики получают куда более мощный инструмент для разработки сложных шаблонов, которые в последствии будет куда проще поддерживать.
Мы говорим, что это одномерный контроль раскладки, но на самом деле у него есть оси x и y. Как вы увидите далее, выравнивание в каждом случае будет происходить с разными свойствами.
Flexbox уже поддерживается всеми современными браузерами, включая даже Internet Explorer, который скоро прикроют. В общем, вы можете смело и уверенно использовать Flexbox в вашем CSS.
Центрируем текст горизонтально и вертикально, используя CSS для выравнивания по центру
Центрирование текста по абсолютному центру традиционно было было одной из самых распространенных проблем с костыльными решениями, которые решил Flexbox. В прошлом было неимоверно много хаков и костылей, таких как использование display: table и т.п. Как я и упоминал ранее, Flexbox сделал этот сложный и неестественный процесс куда более проще.
Для начала, давайте посмотрим на эту разметку, которая демонстрирует то, как отцентрировать текст горизонтально и вертикально.
Это div с элементами заголовков. Мы будем использовать CSS не только для горизонтального центрирования, но и для вертикального. Вы можете вставить любые элементы потомки, такие как
Тут div будет занимать всю доступную ширину и будет минимум в 200px высотой. Это даст нам вертикальные маргины для использования в этом примере.
align-items может использоваться не только для центровки текста вертикально, но и любого дочернего элемента.
Горизонтальное центрирование div’ов с использованием CSS Flexbox
Flexbox делает центровку элементов простым и естественным процессом.
Чтобы выставить по центру дочерние элементы, поставьте justify-content: center для элемента родителя.
Чтобы сделать CSS более юзабельным, я разбил стили по разным селекторам:
Это становится очень удобным при разработке комплексных страниц и когда вам нужна такая же логика в позиционировании. Мне также нравится так делать, потому что таким образом выходит проще читать разметку и накладывать образ предполагаемого макета по ней.
Вертикальное центрирование div’ов с CSS Flexbox
Горизонтальное центрирование никогда не было самым сложным моментом.
Но что у нас с вертикальным центрированием? Ну или как бы мы применили CSS, что вертикально выровнять элементы?
Во многих случаях, это тот момент, при котором большинство разработчиков рвут на себе волосы.
Тут столько правил и костылей, которые нужно запомнить, а ведь всё равно что-нибудь да порушит всю раскладку.
Flexbox наконец-то исправил проблемы с вертикальным центрированием, выдав эту кейсу четкое и понятное правило для применения.
В примере с меню в хедере, враппер навигационной панели отцентрирован вертикально.
Тут элемент хедер служит родителем для навигационной панели, и его ширина равна 100%, а min-height стоит на 80px.
Абсолютное центрирование div’ов с использованием CSS Flexbox
Пока что мы только узнали то, как отцентрировать элементы горизонтально или вертикально. А теперь пора скомбинировать эти два метода.
Для этого я буду снова использовать панель навигации. Нам нужно, чтобы она отрендерилась в абсолютном центре хедера.
Можете посмотреть на то, как я применил этот принцип на полноэкранном фоновом изображении.
Как отцентровать изображение в CSS с помощью text-align и Flexbox
Вообще, изображения могут быть выровнены с использованием свойств text-align и flexbox.
Вы также можете применить флоат слева или cправа, для размещения изображения у желаемой грани контейнера. Я склонен к тому, чтобы использовать флоат, так как обычно я выравниваю изображения внутри текста статьи.
Но тут всё ещё довольно проблематично сделать выравнивание без flexbox. Если вы примените абсолютное центрирование из флексов для контейнера изображения, то вы смело можете выставить картинку по центру обеих осей, ну или только одной, тут уже на ваш выбор.
Просто ради забавы, давайте выровняем изображение с использованием flexbox.
Те же самые правила, что и в примере выше.
Теперь изображение абсолютно центрировано в HTML элементе. Вы можете прописать CSS свойства так, что поменять центровка на вертикальную или горизонтальную.
Заключение
Контроль элементов и позиционирования текста это важнейший аспект при хорошей вёрстке.
В былые времена, центрирование и выравнивание элементов были нудным делом и требовали комбинации из разных костылей.
CSS Flexbox поменял подход к выравниваю элементов. И теперь горизонтальное центрирование, также как и вертикальное стали очень простыми.
Источники информации:
- http://blog.hubspot.com/website/center-text-in-css
- http://css-tricks.com/centering-css-complete-guide/
- http://www.freecodecamp.org/news/html-center-text-how-to-css-vertical-align-a-div/
- http://medium.com/@stasonmars/%D0%B2%D0%B5%D1%80%D1%82%D0%B8%D0%BA%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B5-%D0%B8-%D0%B3%D0%BE%D1%80%D0%B8%D0%B7%D0%BE%D0%BD%D1%82%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B5-%D1%86%D0%B5%D0%BD%D1%82%D1%80%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D0%B2%D1%81%D0%B5%D0%B3%D0%BE-%D0%B8-%D0%B2%D1%81%D1%8F-%D0%B2-css-flexbox-fafd369fc71f