如何使用 div 容器使 div 居中?

发布于 2025-01-11 09:42:20 字数 563 浏览 3 评论 0原文

正如标题所述,我只是想将红色 div 居中。最初,我尝试使用单个红色 div 作为父级,使其垂直和水平居中,但没有运气,经过几次谷歌搜索后,我发现我需要一个父级 div(绿色)才能做到这一点。我对 CSS 真的很烂,只是不断地尝试和错误。

我正在努力简单地将子红色 div 与 3 个子元素( h1 、 h3 和按钮)居中,使用

我所在的

绿色“容器” div 在此处输入图像描述

css

body {
  background: #F5F7FB;
}

.container {
  display: flex;
  width: 100%;
  height: 200px;
  border: 1px solid green;
  
 

}

.container > div {
  margin: auto;
  text-align: center;
  border: 1px solid red;
}

As the title states i am simply trying to center the red div. Initially i tried to use a the single red div as a parent to center it vertically and horizontally but no luck, after a few google searches i had seen that i need a parent div(green) in order to do this. i really suck at css and really just go through trial and error with it.

i'm struggling to simply center the child red div with 3 child elements, the h1 , h3 and button using the green 'container' div

where i'm at

enter image description here

css

body {
  background: #F5F7FB;
}

.container {
  display: flex;
  width: 100%;
  height: 200px;
  border: 1px solid green;
  
 

}

.container > div {
  margin: auto;
  text-align: center;
  border: 1px solid red;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

往事随风而去 2025-01-18 09:42:20

如果您想要将任何元素居中,最好的方法是使用 Flexbox 属性。

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

有关更多详细信息,您可以查看 w3school 使用 flexbox 的指南 https://www.w3schools.com/css /css3_flexbox_container.asp

If you want to center any element, the best way to do that is by using flexbox properties.

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

For more details you can check w3school guide for using flexbox https://www.w3schools.com/css/css3_flexbox_container.asp

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文