简体   繁体   中英

HTML CSS Align two elements the same line

面板

I need to create the above HTML.

It's a h3 with a blue background and to the right is an SVG for a tick.

I need to have both elements sitting on the same line, and the SVG embedded within the 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{ 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:

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.
So it would make sense to just add a class to your <h3> like so:

HTML

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

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.


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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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