# CSS实现多个容器保持相同宽度

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

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

这是一个小伙伴发来的demo

他想让上下这两层啊保持同样的宽度

所以他为了实现这个效果呢

写了一段JS代码

我们先来把这个JS代码

主持解开看一下

效果

就是这样大家看

那他的问题是

除了JS代码我们可不可以用CSS来实现

我们提到保持

相同的宽度或者高度的时候

我们首先会想到flex对吧

我们先来看这个例子

这是一个很简单的两个DIY

然后被套在了一个flex布局里面

我们来看一下啊

那这种布局

他默认就会保持同样的高度

大家看

为什么呢

那是因为哈

flex布局里面他默认有一个属性叫

align-items 他默认是stretch

所以呢他会保持一个相同的高度

如果我们把它改成

flex start

大家看

它就不会相同的高度了

所以我们如果想让两个层

保持同样的高度呢

可以借用flex这个特性

那同样的高度是这样同样的宽度呢

我们这样

把这个代码原封不动放到这个文件里

然后呢把方向改一下

我们用flags election等于cup

大家看这个方向虽然变了

但是他默认flex布局他是（横向）撑满的

他有点像block

所以重点来了

我们如果想让两个层保持同样的宽度

就不能用flex

要用inline-flex

大家再看

这会我在这再加东西他看

他就会保持相同的宽度了

所以呢我们再回到刚才这个例子（demo）

如果想让上下两个层保持同样的宽度

怎么处理呢

我们可以这样

把这两个层啊

单独的放到一个DIY里面

放到这里

然后把这个DIY

把它换成display

等于

line

flex 然后呢

flex direction等于column

我们再来看一下

打开就可以了我在这加一个 contenteditable

好 注意！

大家看 是不是就可以了

最后呢我们留一个小小的思考

就是为什么我们要在中间加一个DIY

而不是在最外层加上 inline-flex 这个属性


---

# 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/css-shi-xian-duo-ge-rong-qi-bao-chi-xiang-tong-kuan-du.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.
