我如何对齐垂直和水平居中的子元素仅在子元素级别设置 css

时间:2021-06-01 19:47:18

标签: html css flexbox

我有一个 html 和 css,我想确保子元素 svg 和 2 个 <p> 元素垂直和水平居中。我已经在我的父元素上尝试了 align-items justify-content 它有效。但它也改变了其他属性。那么是否可以在子元素css级别设置子元素ONLY

html 文件

<div class="container">
  <div class="box">
    <svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   Sorry, your browser does not support inline SVG.
</svg> 
    <p>it should be center</p>
    <p>it should be center on vertical</p>
  </div>
</div>

css 文件

// center horizontally. styles on parent
.container {
  height: 500px;
  width: 700px;
  display: flex;
  border: 1px solid #000000;
}
.box {
  align-self: center;
  align-items: center;
  justify-content: center;
}

https://codepen.io/jacobcan/pen/WNpdWMV

1 个答案:

答案 0 :(得分:1)

您需要将 justify/align 放在父级上。

.container {
  height: 100vh;
  display: flex;
  border: 1px solid #000000;
  align-items: center;
  justify-content: center;
  text-align: center
}
<div class="container">
  <div class="box">
    <svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   Sorry, your browser does not support inline SVG.
</svg>
    <p>it should be center</p>
    <p>it should be center on vertical</p>
  </div>
</div>

相关问题