简体   繁体   中英

HTML/CSS - Left Align and center on same line

I want to left align some text and center another Text on the same line in HTML and CSS. I also want a margin-left on the left-aligned text.

This is my current approach:

HTML :

<div id="wrapper">
  <h1 class="align-left">LEFT</h1>
  <h1>CENTER</h1>
</div>

CSS :

.align-left {
  float: left;
  margin-left: 20px;
}

#wrapper {
  text-align: center;
}

This works with left and right align, but the margin also pushes the centered text. I think this is because the float: left keeps the left-aligned text in the page flow.

Thank you really much :)

Use like this

<div id="wrapper">
  <h1 class="align-left">LEFT</h1>
  <h1 class="align-center">CENTER</h1>
</div>
<style>
h1.align-left {
    text-align:left;
    padding:0;
    margin:0;
    position:absolute;
}

h1.align-center{
  text-align: center;
}
</style>

Other way:

<div id="wrapper">
  <h1 class="align-left">LEFT</h1>
  <h1 class="align-center">CENTER</h1>
</div>
<style>
h1.align-left{
    padding:0;
    margin:0;
    position:absolute;
}
#wrapper {
    text-align:left;
}

h1.align-center{
  text-align: center;
}
</style>

You just need to adjust the HTML:

<div id="wrapper">
  <h1><span class="align-left">LEFT</span>CENTER</h1>
</div>

jsFiddle Demo

If you do not want the center text adjusting as the left text gets longer, use positioning CSS (with the same HTML I've posted).

.align-left {
  position: absolute;
  left: 20px;
}

#wrapper {
  text-align: center;
  position: relative;
}

jsFiddle Demo for positioning

Be aware... if you don't want the center text to adjust, it is possible that the text is going to overlap.

My two cents.

CSS code:

h1{
  display: inline-block;
}
#center{
  text-align: center;
  width: 80%;
}

#wrapper {
  width: 100%;
}

HTML code:

<div id="wrapper">
  <h1 id="left">LEFT</h1>
  <h1 id="center">CENTER</h1>
</div>

You can achieve it with the code below. The order of the articles tags won't matter, the css takes care to position them correctly.

 <!DOCTYPE html> <html> <head> <style type="text/css"> section { border: 1px solid #ff0000; overflow: hidden; position: relative; width: 100%; } section article.txt { border: 1px solid green; max-width: 35%; } section article.left { float: left; } section article.right { float: right; } section article.center { --width: 300px; position: absolute; margin: 0 50%; left: calc((var(--width) / 2) - var(--width)); width: var(--width); } </style> </head> <body> <section> <article class="txt left">Text LEFT side</article> <article class="txt right">Text RIGHT side</article> <article class="txt center">Text CENTER</article> </section> </body> </html> 

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