This question already has answers here:
How to Vertical align elements in a div?
                                
                                    (28个答案)
                                
                        
                        
                            Vertically align text next to an image?
                                
                                    (21个回答)
                                
                        
                        
                            Flexbox: center horizontally and vertically
                                
                                    (11个答案)
                                
                        
                                上个月关闭。
            
                    
您好,我是HTML和CSS的新手,我正在尝试创建一个仅供学习的网站。我只是做了一个标题,并在其中放置了徽标,但是我无法将其设置为垂直对齐。有人可以解释吗?

这是HTML文件:

<!DOCTYPE html>




<head>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Scienitive</title>
</head>
<body>
    <div class="header">
        <div class="logo-container">
            <div class="logo">
                <a href ="index.html"><img src ="logo.png"></a>
            </div>
            <h1>Scienitive</h1>
        </div>
    </div>
</body>




这是CSS文件:

.header {
width: 100%;
height: 80px;
display: block;
background-color: #FF5733;
}
.logo-container {
height: 100%;
display: table;
float: left;
}
.logo-container h1{
color: white;
height: 100%;
display: table-cell;
vertical-align: middle;
font-family: "Open Sans";
font-size: 48px;

}
.logo {
display: table;
height: 80px;
}
.logo img{
width: 48px;
height: 48px;
vertical-align: middle;
display: table-cell;
}


这是网站的样子
Image

最佳答案

实际上,您实际上不想直接在display: table-cell标记上设置vertical-align: middleimg,而是在其容器/父项上设置:



.header {
  width: 100%;
  height: 80px;
  display: block;
  background-color: #FF5733;
}

.logo-container {
  height: 100%;
  display: table;
  float: left;
}

.logo-container h1 {
  color: white;
  height: 100%;
  display: table-cell;
  vertical-align: middle;
  font-family: "Open Sans";
  font-size: 48px;
}

.logo {
  display: table-cell;
  vertical-align: middle;
  height: 80px;
}

.logo img {
  width: 48px;
  height: 48px;
}

<head>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="style.css">
  <title>Scienitive</title>
</head>

<body>
  <div class="header">
    <div class="logo-container">
      <div class="logo">
        <a href="index.html"><img src="//placehold.it/48x48"></a>
      </div>
      <h1>Scienitive</h1>
    </div>
  </div>
</body>

10-05 20:42
查看更多