# 水平居中、垂直居中

## 一、行内元素

* 水平：`text-align: center`
* 垂直：`line-height: {父元素高度}px`

## 二、块状元素

### 1、子元素宽高确定：

方式1：绝对定位 + 各方向为0 + margin:auto

{% embed url="<https://codepen.io/yuyy/full/GRXvajY>" %}

方式2：绝对定位 + left/top:50% + margin-left/margin-top: 宽/高一半

{% embed url="<https://codepen.io/yuyy/full/XWPerMp>" %}

### 2、子元素宽高不确定

绝对定位 + left/top:50% + transform: translate(-50%)

{% embed url="<https://codepen.io/yuyy/full/rNZzgJy>" %}

## 三、万能方案

flex

```css
.center{
    display: flex;
    justify-content: center;
    align-items: center;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.yuyy.tech/mian-shi-shu-li/qian-duan-ji-chu/css/shui-ping-ju-zhong-chui-zhi-ju-zhong.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
