Home >Web Front-end >CSS Tutorial >How can I align inline-blocks left and right on a single line?

How can I align inline-blocks left and right on a single line?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 10:24:31544browse

How can I align inline-blocks left and right on a single line?

Aligning Inline-Blocks Left and Right on a Single Line

When working with inline-blocks, it can be challenging to align them precisely on a single line. This article provides two solutions to this problem: Flexbox and text-align justification.

Flexbox Solution

Flexbox offers an elegant and concise solution. By applying display: flex; to the parent container and justify-content: space-between; to align the child elements, you can easily achieve the desired alignment.

<code class="css">.header {
  display: flex;
  justify-content: space-between;
}</code>

Text-Align Justification Solution

Using text-align justification is another viable option. Here's an example CSS code that combines the technique with some browser-specific hacks for better compatibility:

<code class="css">.header {
  background: #ccc; 
  text-align: justify; 

  /* ie 7*/  
  *width: 100%;  
  *-ms-text-justify: distribute-all-lines;
  *text-justify: distribute-all-lines;
}
 .header:after{
  content: '';
  display: inline-block;
  width: 100%;
  height: 0;
  font-size:0;
  line-height:0;
}

h1 {
  display: inline-block;
  margin-top: 0.321em; 

  /* ie 7*/ 
  *display: inline;
  *zoom: 1;
  *text-align: left; 
}

.nav {
  display: inline-block;
  vertical-align: baseline; 

  /* ie 7*/
  *display: inline;
  *zoom:1;
  *text-align: right;
}</code>

This approach works well across different browsers, including IE7 and above.

Remember, if inline-block elements are not separated by space, the text-align justification solution may not work. Additionally, setting the font-size of the parent element to 0 and resetting it back to a desired value for child elements can help remove extra space introduced by the after pseudo-element.

The above is the detailed content of How can I align inline-blocks left and right on a single line?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn