Sunday, March 14, 2021

CSS - divs side by side flexbox examples

Below are examples with <div>'s side by side styled with flexbox:

  1. two <div>'s with equal widths
  2. two <div>'s one with fixed width and other expanding width
  3. three <div>'s with defined percentage widths


cherryshoe.html

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="cherryshoe.css">
<title>cherryshoe</title>
</head>
<body>
    <h3>Flexbox - divs side by side</h3>
    <p>Example 1: equal widths</p>
    <div class="container-equal">
        <div class="container-equal-child">Left 50%</div>
        <div class="container-equal-child">Right 50%</div>
    </div>
    <p>Example 2: left taking up remaining, right fixed with</p>
    <div class="container-different">
        <div class="container-different-left">Left will expand to fill space</div>
        <div class="container-different-right">Right fixed width</div>
    </div>
    <p>Example 3: with defined percentage widths</p>
    <div class="container-thirds">
        <div class="container-thirds container-thirds-child-left">Left with 20%</div>
        <div class="container-thirds container-thirds-child-center">Center with 30%</div>
        <div class="container-thirds container-thirds-child-right">Right with 50%</div>
    </div>
</body>
</html>

cherryshoe.css

.container-equal {
  display: flex; /* define flex container with default row directioin */
}
.container-equal-child{
  flex: 1;  /* grow */
  background: orange;
}
.container-equal-child:first-child{
  flex: 1;  /* grow */
  background: yellow;
 }

.container-different {
  display: flex;
}
.container-different-left{
  flex: 1;  /* grow */
  background: yellow;
}
.container-different-right {
  flex: 0 0 250px; /* flex-grow 0, flex-shrink 0, flex-basis with fixed width */
  background: orange;
}

.container-thirds {
  display: flex;
  width: 100%; 
  background: yellow;
}
.container-thirds .container-thirds-child-left {
  width: 20%; 
}
.container-thirds .container-thirds-child-center {
  width: 30%; 
  background: orange;
}
.container-thirds .container-thirds-child-right {
  width: 50%; 
  background: pink;
}

Flexbox is supported in modern browsers:



No comments:

Post a Comment

I appreciate your time in leaving a comment!