# justify-content垂直居中，缩小容器后顶部丢失的bug

{% embed url="<https://v.douyin.com/rkdQhJb/>" %}

{% embed url="<https://www.bilibili.com/video/BV1HP411g7ZL/>" %}

这是一个小伙伴发来的demo

他说啊为什么浏览器缩小之后

上面那个1就没有了

即使用滚动条也滚不上去了

但是下边（的5）没问题

为什么会这样呢

因为啊他用了一个justify-content配合flex

做了这么一个垂直居中的效果

所以无论什么时候他都是垂直居中的

即便是浏览器的高度小于了内容高度

他也是垂直居中的

所以就会导致

会有上下两部分空间在屏幕外边

下边的没问题

但上面的那部分他就看不着了

为什么呢我们来看这个demo

这个是一个可以拖拽的容器

当把容器拖拽到屏幕下边的边缘

大家看他就会出现纵向滚动条

当我们把这个容器拖拽到右边

超出屏幕边缘呢

他就会出现横向滚动条

但是如果我把这容器拖拽到上面

他就没有滚动条

或者左边也是一样的

所以呢有些时候

我们就会把一些容器放置到

横/纵 坐标为负数的屏幕外边

这样的话呢就可以把它隐藏起来

然后呢再做一些动画

比如说这样向下滑出

那再回到刚才这个例子

这种情况怎么解决呢

最好的方法肯定是当它缩小的时候呢

就不要这个垂直居中了

大家看这个1就出来了

然后呢当它放大的时候呢

再把这垂直居中加上

但是呢这种效果（如果不用js）就依赖于媒体查询了

就是这个media

之前我提到过哈

那但是有个问题这种使用方法

在这里边啊需要设

置一个max-height

这个值是固定的

也就意味着

页面上这个数量和高度

都只能是固定的了

所以啊这个思路也不是特别好

我们可以换一种实现垂直居中的思路

我们不用这种方法了

我们利用margin:auto的方式来实现

垂直居中

但是呢这里边注意

它有很多个子元素

所以我们需要借助一下伪类

我们这样father

然后里边的first child

给它加一个margin:top: auto

然后同理呢

再来一个last child

然后还是margin-bottom auto

大家看居中了

然后再缩小

大家看这样就没有问题了


---

# 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://sunzsh.gitbook.io/xiaoshan.bug/justifycontent-chui-zhi-ju-zhong-suo-xiao-rong-qi-hou-ding-bu-diu-shi-de-bug.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.
