Home >Web Front-end >CSS Tutorial >How to Create a 3-Column Layout with CSS Without Modifying HTML?

How to Create a 3-Column Layout with CSS Without Modifying HTML?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-14 14:15:02393browse

How to Create a 3-Column Layout with CSS Without Modifying HTML?

How to Create a 3-Column Layout with CSS Without Modifying HTML

Using HTML, you have a container containing three columns, each with a distinct class ("column-left", "column-center", and "column-right"). The goal is to arrange these columns horizontally without modifying the HTML structure through CSS.

SOLUTION

To achieve this desired layout, incorporate the following CSS rules:

.column-left {
  float: left;
  width: 33.333%;
}

.column-right {
  float: right;
  width: 33.333%;
}

.column-center {
  display: inline-block;
  width: 33.333%;
}

This CSS ensures that the left and right columns float to their respective sides of the container, while the center column is displayed in the remaining space.

DEMO

<div class="container">
  <div class="column-center">Column center</div>
  <div class="column-left">Column left</div>
  <div class="column-right">Column right</div>
</div>

ENHANCED GRID SYSTEM

To extend this approach to multiple columns, consider creating a simple grid system. For a five-column layout, for instance, the following CSS would suffice:

.column {
  float: left;
  position: relative;
  width: 20%;
  
  /*for demo purposes only */
  background: #f2f2f2;
  border: 1px solid #e6e6e6;
  box-sizing: border-box;
}

.column-offset-1 {
  left: 20%;
}
.column-offset-2 {
  left: 40%;
}
.column-offset-3 {
  left: 60%;
}
.column-offset-4 {
  left: 80%;
}

.column-inset-1 {
  left: -20%;
}
.column-inset-2 {
  left: -40%;
}
.column-inset-3 {
  left: -60%;
}
.column-inset-4 {
  left: -80%;
}

With this enhanced grid, you can position columns precisely by applying appropriate offset or inset classes.

The above is the detailed content of How to Create a 3-Column Layout with CSS Without Modifying HTML?. 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