将图像添加到居中标题而不移动文本对齐

时间:2018-01-19 12:18:07

标签: html css

是否可以将图像添加到居中的h1元素,而文本对齐方式根本没有变化?

换句话说,图像不会居中,而是位于文本左侧,图像与文本之间的间距为20像素。它不会一直在页面左侧。无论图像的大小如何,文本都将居中于同一位置。

我的代码当前移动文本以调整图像,如下所示:

<h1 style="text-align: center;">
   <img src="logo.png" alt="logo" width="50px" height="auto">Centered Text
</h1>

4 个答案:

答案 0 :(得分:3)

如果您能够在文本周围添加<span>,则可以使用绝对位置放置图像(您必须使用calc()将其对齐:100%+您的距离跨度边缘20 px):

&#13;
&#13;
h1 span {
  position: relative;
}
h1 span img {
  position: absolute;
  right: calc(100% + 20px);
}
&#13;
<h1 style="text-align: center;">
  <span><img src="http://via.placeholder.com/50x50" alt="logo" width="50px" height="auto">Centered Text</span>
</h1>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

是的CSS-Grid

h1 {
  width: 90%;
  margin: 1em auto;
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  border: 1px solid grey;
  position: relative;
  align-items: center;
}

h1::before {
  content: "";
  position: absolute;
  left: 50%;
  height: 200%;
  width: 1px;
  background: red;
}

img {
  margin-left: auto;
  margin-right: 20px;
}
<h1>
  <img src="http://www.placebacon.net/400/300" alt="logo" width="50px" height="auto">Centered Text
</h1>

<h1>
  <img src="http://www.placebacon.net/400/300" alt="logo" width="100px" height="auto">Centered Text
</h1>

答案 2 :(得分:0)

&#13;
&#13;
<button class="menu">hover me!</button>
<h1>some content</h1>

<p> "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
&#13;
.block-panel{
}

.block-panel .img-block{
    display: inline-block;
    float: left;
    margin-right: 5px;
}

.block-panel .text-block{
    line-height: 50px;
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

<h1 style="text-align: center;">
   <img src="http://via.placeholder.com/50x50" alt="logo" width="50px" height="auto" style="
    margin: 0 auto;
    float: initial;
    display: inherit;">Centered Text
</h1>