Как в html сделать текст по центру страницы
Перейти к содержимому

Как в html сделать текст по центру страницы

  • автор:

Text Align in CSS – How to Align Text in Center with HTML

Text Align in CSS – How to Align Text in Center with HTML

There will be many times where you will need to center some text using HTML and CSS. But what is the best way to go about that?

In this article, I will show you how to use the text-align property in CSS and show you how to vertically align text using CSS Flexbox. I will also talk about the <center> tag and why you shouldn’t use it to center text.

How to Use the text-align Property in CSS

When you are working with heading or paragraph tags, the default styling in HTML will position the text on the left hand side of the page.

In this example, we have an <h1> which is placed on the upper left hand side of the page.

Screen-Shot-2022-04-24-at-11.41.12-AM

If we wanted to horizontally center that text on the page, then we can use the text-align property.

Screen-Shot-2022-04-24-at-11.42.48-AM

If you wanted to horizontally center all of the text on the page, then you can use the text-align property in the body selector.

In this next example, we have some more text in our HTML.

Without any styling, it currently looks like this on the page.

Screen-Shot-2022-04-24-at-12.30.14-PM

In our CSS, we can target the body selector and use the text-align property.

Screen-Shot-2022-04-24-at-12.29.56-PM

How to Horizontally and Vertically Center Text

The text-align property is used to horizontally center text on the page. But we can also use CSS Flexbox to vertically center the text.

In this example, we have some text in our HTML:

This is what it currently looks like without any styling.

Screen-Shot-2022-04-24-at-12.35.30-PM

We can center the <h2> using the text-align property.

Screen-Shot-2022-04-24-at-12.42.49-PM

We can then horizontally and vertically center the paragraph inside the flex-container div using Flexbox.

Screen-Shot-2022-04-24-at-12.58.57-PM

Should you use the center tag?

In older versions of HTML, the <center> tag was used as a way to center text horizontally on the page.

Screen-Shot-2022-04-24-at-12.14.09-PM

A lot of new developers will still use this tag because it does display the correct results. However, the <center> tag was deprecated in HTML 4 because best practice is to use the CSS text-align property instead.

Screen-Shot-2022-04-24-at-12.16.58-PM

This is the deprecation warning from MDN docs

It is important to remember that HTML is for content while CSS is for styling. It is best practice to separate those two concerns and not use HTML for styling purposes.

I hope you enjoyed this article on how to center text using HTML and CSS.

Как выровнять текст по центру в html

Аватар пользователя Вячеслав Межуревский

Выравнивание текста отвечает за его внешний вид, формирование краев абзаца. Обычно текст обрамляют тегами <p> или <div> и затем применяют css свойство text-align со следующим значением:

  • по левому краю — left
  • по правому краю — right
  • по центру — center
  • по ширине — justify

Выравнивание элементов по левому краю задано по умолчанию, поэтому указывать его лишний раз необходимости нет. Отличие между абзацем (тег <p>) и тегом <div> в том, что в начале и конце параграфа появляется вертикальный отступ, чего нет в случае использования тега <div>.

Centering Text in HTML

I know at first this seems like a very stupid question, but I have a good reason for asking it. Even though I might just be misled.

For EVER I have been using the <center>Text</center> tag to have text appear centered horizontally.

Apparently this tag is depreciated, and is no longer used. So I have tried using <p align=»center»>Text</p> although it seems to be buggy and I have read that It does not work in all browsers.

On top of that, when I have a header <h#> tag within a <p> tag there is also a validation issue.

The point is, I want to do this right, and although the center tag is tolerable, it is apparently not the best way to go. Why has it been depreciated? And what is your alternative? I honestly have no idea where to go from here.

P.S. Asking this question kills me inside.

Even while using the accepted answer;

I am not able to center <h> tags within the <p> tags. I have tried and read that <h# align=»center»> does not work in all browsers and I have tried applying the style to the header tag with no avail. What do you think?

15 Answers 15

The text alignment needs to be declared in CSS. You can do this in a CSS section at the top of the file, in a separate file, or in the element itself. The simplest method would be the latter (note that this method is not generally considered a good practice):

If you want to put it at the top of the html file, it would look like this:

The best method would be to have a separate CSS stylesheet containing the CSS. Then, add a link to the CSS in the <head></head> section of your html:

Clayton's user avatar

That will do the trick for you

Josh Mein's user avatar

try <p style=»text-align: center;»>Text</p>

or at the top of your html you can declare:

then later just apply the class:

just remember the text-align css property will work for block elements.

The politically correct way to do it is CSS.

Try to do something like:

Or even better, use a CSS stylesheet.

Really, you should not be using in-line CSS either, it is just as sloppy. You can define a style for all <p> tags, or attach a class like <p and define the header class in CSS like:

This way your style is separated from your HTML, producing a much cleaner HTML file.

Regarding a <h#> tag within a <p> tag, that is indeed a validation issue.

<h#> tags are meant to mark up headings. <p> tags are meant to mark up paragraphs.

So, if I was marking up your question, I might start like this:

If I wanted the heading to be center aligned, I’d again use CSS:

Paul D. Waite's user avatar

To address the implied second question, the reason you have validation issues when you have a <h#> inside a <p> is because nesting headers inside of paragraphs is not allowed in HTML 4.0 and XHTML.

To expound, headings and paragraphs are semantic concepts, meant to inform the structure of your document and not imply anything about the appearance of their content (granted, they do appear different by default but that’s not the point of their usage). It follows that a heading shouldn’t be contained within a paragraph.

If your implementation calls for nesting headers inside of paragraphs you might want to rethink your approach to what you’re trying to accomplish. If the intent is to indicate structurally «this is a heading», consider why a heading would be inside a paragraph. If the intent is to make certain text within a paragraph look different, then you would want to use one of the inline elements such as a span or em, with associated CSS styling.

CSS Layout — Horizontal & Vertical Align

Setting the width of the element will prevent it from stretching out to the edges of its container.

The element will then take up the specified width, and the remaining space will be split equally between the two margins:

This div element is centered.

Example

Note: Center aligning has no effect if the width property is not set (or set to 100%).

Center Align Text

To just center the text inside an element, use text-align: center;

This text is centered.

Example

Tip: For more examples on how to align text, see the CSS Text chapter.

Center an Image

To center an image, set left and right margin to auto and make it into a block element:

Paris

Example

Left and Right Align — Using position

One method for aligning elements is to use position: absolute; :

In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.

Example

Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.

Left and Right Align — Using float

Another method for aligning elements is to use the float property:

Example

The clearfix Hack

Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the «clearfix hack" to fix this (see example below).

Without Clearfix

With Clearfix

Then we can add the clearfix hack to the containing element to fix this problem:

Example

Center Vertically — Using padding

There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding :

I am vertically centered.

Example

To center both vertically and horizontally, use padding and text-align: center :

I am vertically and horizontally centered.

Example

Center Vertically — Using line-height

Another trick is to use the line-height property with a value that is equal to the height property:

I am vertically and horizontally centered.

Example

.center <
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
>

/* If the text has multiple lines, add the following: */
.center p <
line-height: 1.5;
display: inline-block;
vertical-align: middle;
>

Center Vertically — Using position & transform

If padding and line-height are not options, another solution is to use positioning and the transform property:

I am vertically and horizontally centered.

Example

.center <
height: 200px;
position: relative;
border: 3px solid green;
>

.center p <
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
>

Tip: You will learn more about the transform property in our 2D Transforms Chapter.

Center Vertically — Using Flexbox

You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions:

Example

Tip: You will learn more about Flexbox in our CSS Flexbox Chapter.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *