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

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

  • автор:

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.

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?

You can center a block-level element by giving it margin-left and margin-right of auto (and it has a set width , otherwise it would be full width and wouldn’t need centering). That’s often done with shorthand like this:

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.

2) In your “is it block level” -> “is the element of unknown height” you proceed to give the parent an explicit height. To me, that defeats the purpose of trying to handle the unknown-height scenario. If I don’t know the height of the child, it’s quite common for me to also not know the height of the parent.

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

Re #4: Really the same point as #2, although I didn’t catch that pos: absolute was part of this one as well, which does kind of distract from the height issue ( the fact that the elements are layered on top of each other is a more eye-catching layout bug than the fact that they’re not vertically centered.): http://codepen.io/anon/pen/rjflG .

Sorry, I am kind of misinterpreted, misrepresenting what you are doing with #1. Truce there, as well.

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

Изучив рубрику «CSS», вы узнаете, как с помощью каскадных таблиц стилей (CSS) можно легко управлять дизайном сайта и упростить создание самого сайта. Данная рубрика заменит Вам полноценный «учебник по CSS».

Бесплатные уроки CSS для начинающих

Вдобавок к текстовым урокам по каскадным таблицам стилей, в данном разделе также представлены полезные уроки 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:

  • Line-relative values vertically align an element relative to the entire line.
  • Values for table cells are relative to the table-height-algorithm, which commonly refers to the height of the row.

It is important to note that it is possible to nudge text vertically up or down in CSS using the vertical-align property. This property sets the vertical alignment of an inline or table-cell element, and can be used to adjust the vertical position of text within its container.

Note that vertical-align only applies to inline or table-cell elements, so it may not work as expected on block-level elements such as <div> or <p> . In such cases, you may need to wrap the text in an inline or table-cell element to apply vertical-align .

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

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