如何使标题中的图像左对齐和垂直对齐,并使文本水平保持在div的中心位置

问题描述 投票:1回答:2

我正在此页眉中寻求图像的左对齐和垂直对齐。

@import url("https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700");
* {
  box-sizing: border-box;
}

img {
  float: left;
  vertical-align: middle;
}

.header {
  padding: 5px;
  text-align: center;
  background: #222222;
  color: white;
  font-size: 20px;
}

h2 {
  color: white;
}

title {
  color: white;
}

body {
  font-family: 'Open Sans', sans-serif;
  background-color: #2C2C2C;
}
<div class="header" class="frame">
  <img src="https://i.imgur.com/pZIRNtP.png" class="logo" alt="logo" />
  <h2>This should be center</h2>
</div>

这是我的图像代码(当前为左对齐,但似乎无法垂直对齐。然后,当文本应水平位于div中心时,它也将文本向右移动)

img {
    float:left;
    vertical-align: middle;
}

我基本上需要红色图像保持相同的大小,我只需要将其左对齐(可能距左50px)并与标题div垂直对齐即可。但是我还需要文本保持在div,vert和horz的中心。

html css image center
2个回答
0
投票

您可以将display: flex;用于标题,然后将flex-grow: 1;用于h2以占用剩余空间。

@import url("https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700");
* {
  box-sizing: border-box;
}

img {
  float: left;
  vertical-align: middle;
}

.header {
  padding: 5px;
  text-align: center;
  background: #222222;
  color: white;
  font-size: 20px;
  display: flex;
  align-items: center;
}

h2 {
  color: white;
  flex-grow: 1;
}

title {
  color: white;
}

body {
  font-family: 'Open Sans', sans-serif;
  background-color: #2C2C2C;
}
<div class="header" class="frame">
  <img src="https://i.imgur.com/pZIRNtP.png" class="logo" alt="logo" />
  <h2>This should be center</h2>

</div>

0
投票

一种方法:

@import url("https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700");
* {
  box-sizing: border-box;
}

img {
  vertical-align: middle;
}

.header {
  padding: 5px;
  background: #222222;
  color: white;
  font-size: 20px;
}

h2 {
  color: white;
  text-align: center;
  margin-top: -45px;
}

title {
  color: white;
}

body {
  font-family: 'Open Sans', sans-serif;
  background-color: #2C2C2C;
}
<div class="header" class="frame">
  <img src="https://i.imgur.com/pZIRNtP.png" class="logo" alt="logo" />
  <h2>This should be center</h2>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.