Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css divide width 100% to 3 column

Tags:

html

css

I have a layout where I have 3 columns.

Therefore, I divide 100% by 3.

The result is obviously 33.333....

My goal is perfect 1/3 of screen.

Question:

How many numbers after dot can CSS handle to specify 1/3 of width ?

e.g. 33.33333 (n=5) ← how many n can css handle

HTML:

<div id="wrapper">     <div id="c1"></div>     <div id="c2"></div>     <div id="c3"></div> </div> 

CSS:

#c1, #c2, #c3 {     width: 33%; // 1/3 of 100% } 

Is there a better way to divide by 3?

like image 780
Ing. Michal Hudak Avatar asked Sep 13 '13 08:09

Ing. Michal Hudak


People also ask

How do I divide a div into 3 columns?

In the main <div> element, you are supposed to include a class with the attribute “row”, which is going to tell your browser to take up the entire space for this row on the web page. Now, you are ready to divide this row into columns by including three <div> elements containing the class with a “column” attribute.


1 Answers

As it's 2018, use flexbox - no more inline-block whitespace issues:

body {   margin: 0; }  #wrapper {   display: flex;   height: 200px; }  #wrapper > div {   flex-grow: 1; }  #wrapper > div:first-of-type { background-color: red } #wrapper > div:nth-of-type(2) { background-color: blue } #wrapper > div:nth-of-type(3) { background-color: green }
<div id="wrapper">   <div id="c1"></div>   <div id="c2"></div>   <div id="c3"></div> </div>

Or even CSS grid if you are creating a grid.

body {   margin: 0; }  #wrapper {   display: grid;   grid-template-columns: repeat(3, 1fr);   grid-auto-rows: minmax(200px, auto); }  #wrapper>div:first-of-type { background-color: red } #wrapper>div:nth-of-type(2) { background-color: blue } #wrapper>div:nth-of-type(3) { background-color: green }
<div id="wrapper">   <div id="c1"></div>   <div id="c2"></div>   <div id="c3"></div> </div>

Use CSS calc():

body {   margin: 0; }  div {   height: 200px;   width: 33.33%; /* as @passatgt mentioned in the comment, for the older browsers fallback */   width: calc(100% / 3);   display: inline-block; }  div:first-of-type { background-color: red } div:nth-of-type(2) { background-color: blue } div:nth-of-type(3) { background-color: green }
<div></div><div></div><div></div>

JSFiddle


References:

  • How to remove the space between inline-block elements?
  • MDN calc()
  • Can I Use calc()
like image 160
Vucko Avatar answered Oct 04 '22 16:10

Vucko