首页 > 解决方案 > 我无法使用 flexbox 在标题中居中 H1

问题描述

我正在尝试学习 flexbox,并且正在努力将文本集中在标题中的 div 中。我在左边有一个图像,然后是一个带有 text_box 的差异,我正在尝试使用 justify-content: center 将 h1 居中,但无论我放什么它都不会移动文本。我可以让文本居中的唯一方法是使用 margin: 0 auto; 但这似乎也更向右。

代码:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Montserrat', sans-serif;
    font-weight: 400;
    font-size: 1em;
    line-height: 1.7;
    color: #777;
    padding: 20px;
}

.header {
    display: flex;
    flex-wrap: wrap;

    height: 60vh;
    background-image: linear-gradient(
        to right bottom,
        rgba(12, 186, 186, 0.5), 
        rgba(56, 0, 54, 0.5)),
        url(../img/code.jpg);
    background-size: cover;
    background-position: top;
    clip-path: polygon(0 0, 100% 0, 100% 55vh, 0 100%);
   /* Defines how to distribute the empty space between child elements */
   color: #fff;
   padding: 40px;

}

.header_img img {
    display: flex;
    width: 100%;
    border-radius: 82%;
    padding: 0;
}

.header_text {
    justify-content: center  
}



hr {
    display: flex;

}

@media screen and (max-width: 576px) {
    .text_box h1 {
      font-size: 1.4em;
    }
    .text_box h2 {
        font-size: 1.2em;
    }

    .header {
        justify-content: center;
    }

    .header_img {
        display: flex;
    }
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./assets/css/style.css">
</head>
<body>
     <header class="header">
        <div class="header_img">
           <img src="assets/img/stephen_moore_london_2012.jpg" alt="">
        </div>
        <<div class="header_text">
               <h1>My Name</h1>
               <hr>
               <h2>Something Here</h2>
        </div>
    </header>

</body>
</html>

标签: cssflexbox

解决方案


更新 header_text 类:

.header_text {
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
    flex: 1;
    align-items: center;
    justify-content: center;
}

推荐阅读