简体   繁体   English

HTML CSS将两个元素对齐在同一行

[英]HTML CSS Align two elements the same line

面板

I need to create the above HTML. 我需要创建上面的HTML。

It's a h3 with a blue background and to the right is an SVG for a tick. 这是带有蓝色背景的h3,右侧是刻度线的SVG。

I need to have both elements sitting on the same line, and the SVG embedded within the h3. 我需要将两个元素都放在同一行上,并将SVG嵌入h3中。

This looks so easy, but I can't figure out how to do this. 这看起来很简单,但是我不知道该怎么做。

What is the best way to achieve the above? 实现以上目标的最佳方法是什么?

<h3 style="background-color:blue;">About You 
    <img src="image.png" style="float:right;display:block;">
</h3>

Simply create a <h3> with a image in it and apply padding to <h3> for top and bottom space. 只需创建一个带有图像的<h3>并将填充应用于<h3>的顶部和底部空间。

 h3{ font-family:arial; font-size:18px; color:#fff; background:blue; margin:0; padding:5px 10px; } h3 img{ float:right; } 
 <h3>About Us <img src="tick.png"></h3> 

As the others already answered what CSS to use, I just want to promote an additional approach: 正如其他人已经回答了要使用的CSS一样,我只想提倡一种其他方法:

Assuming you have multiple headlines with the styled tick, it makes sense not always have to add the whole <img /> tag with all its properties everytime. 假设您的样式标题带有多个标题,则不必每次都添加带有其所有属性的整个<img />标签是有意义的。
So it would make sense to just add a class to your <h3> like so: 因此,将类添加到您的<h3>就像这样:

HTML 的HTML

<h3 class="blue-bg tick">About You</h3>

CSS 的CSS

h3.blue-bg {
  background: blue;
  /* and what else you need */
}
h3.tick:after {
  content: '';
  background-image: url("/path/to/your/image-tick.svg");

  /* you need to define the dimensions: */
  background-size: 18px 18px;
  width: 18px; height: 18px;

  /* and what else you need */
}


So you can just add your defined class to every element instead of a huge junk of HTML. 因此,您只需将定义的类添加到每个元素中,而不必添加大量的HTML。


Complete Snippet to try out and fiddle with: 完整的代码段可以尝试并摆弄:

 h3.blue-bg { background: #21abe2; /* and what else you need */ font-family: helvetica, arial; font-size: 18px; color: #fff; margin: 0; padding: 5px 10px; } h3.blue-bg.dark { background: blue; font-style: italic; } h3.tick:after { content: ''; background: transparent url("https://upload.wikimedia.org/wikipedia/commons/2/27/White_check.svg") no-repeat center; background-size: 18px 18px; /* and what else you need */ display: block; float: right; width: 18px; height: 18px; } 
 <h3 class="blue-bg tick">About You</h3> <br/> <h3 class="blue-bg tick">Another crazy Headline</h3> <br/> <h3 class="blue-bg dark tick">Even with other styles defined</h3> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM