设置宽高之后还能居中
时间: 2023-07-04 14:08:57 浏览: 55
可以,可以通过设置该元素的 `margin` 属性来实现。具体来说,可以将该元素的左右上下四个方向的 `margin` 值都设置为 `auto`,这样就可以实现该元素在父容器中水平和垂直方向上的居中。
示例代码如下:
```html
<style>
.container {
width: 500px;
height: 300px;
border: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 100px;
height: 100px;
background-color: red;
margin: auto;
}
</style>
<div class="container">
<div class="box"></div>
</div>
```
在这个示例中,我们将 `.container` 设置为一个固定宽度和高度的容器,并且使用 `display: flex`、`justify-content: center` 和 `align-items: center` 属性使得其内部元素在水平和垂直方向上都居中。而 `.box` 则是一个需要居中显示的元素,我们通过将其 `margin` 属性设置为 `auto` 来实现其在 `.container` 内居中显示。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![.rar](https://img-home.csdnimg.cn/images/20210720083646.png)
![.rar](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)