Home How to give flex items equal width?

# How to give flex items equal width?

Andrea Anfuso
1#
Andrea Anfuso Published in 2017-09-14 09:38:29Z
 I would like the first and last elements to have the same width. How to do it? main { display: flex; justify-content: space-between; width: 100%; } input { width: 200px; } 
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
 JSFiddle: https://jsfiddle.net/7nz07sqn/9/
kukkuz
2#
 Give flex: 0 0 auto to the middle div (so that it occupies as much width as its contents have) and flex: 1 for the other two divs (adding borders for illustration) Note that this solution assumes the middle div has a fixed width (you've given your input a fixed width) - see demo below: main { display: flex; justify-content: space-between; width: 100%; } input { width: 200px; } main > div { border: 1px solid; } main div:first-child, main div:last-child { flex: 1; } main div:nth-child(2) { flex: 0 0 auto; } 
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit,

Michael_B
3#
 To make the first and last elements equal width, just give them flex: 1. main { display: flex; } input { width: 200px; } main > div:first-child, main > div:last-child { flex: 1; } 
 This tells the first and last items to consume equal distributions of the free space in the container. Because the middle div (with the input) is occupying 200px of width, the siblings with flex: 1 share the remaining space (100% - 200px). The flex: 1 rule is a shorthand for flex: 1 1 0, which breaks down to: flex-grow: 1 flex-shrink: 1 flex-basis: 0 The first and last divs were not equal width to begin with because the initial setting for flex-basis is auto. This means that items are sized based on the length of their content.