3

Is it possible to horizontally center .div2 without position absolute/fixed like this image?

enter image description here

div3 can change width

Here's my code:

body {
  margin:0;
}

.test {
  background:green;
  color:#fff;
  display:flex;
}

.test .div1 {
  
}

.test .div2 {
  margin:0 auto;
background:red;
}

.test .div3 {
  margin:0 0 0 auto;
}
<div class="test">
  <div class="div1">Left options</div>
  <div class="div2">Center div</div>
  <div class="div3">Username: test (string can change)</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Moor Wead
  • 43
  • 1
  • 4

5 Answers5

0

give display flex to parent element. then justify-contents aligns child on main axis and `align-items' align child vertically.
Get more details https://css-tricks.com/snippets/css/a-guide-to-flexbox/

<div class="test">
  <div class="div1">Left options</div>
  <div class="div2">Center div</div>
  <div class="div3">Username: test (string can change)</div>
</div>
<style>
.test{
display: flex;
justify-content: space-between;
align-items: center;
height: 50px;
}
</style>
yPhil
  • 8,049
  • 4
  • 57
  • 83
Jagajit Prusty
  • 2,070
  • 2
  • 21
  • 39
0

You can give all the divs 33.3333% width

.test {
  background:green;
  color:#fff;
  display:flex;
}

.test .div1 {
  width:33.3333%;
}

.test .div2 {
  margin:0 auto;
background:red;
  width:33.3333%;
}

.test .div3 {
  margin:0 0 0 auto;
    width:33.3333%;
}
<div class="test">
    <div class="div1">Left options</div>
    <div class="div2">Center div</div>
    <div class="div3">Username: test (string can change)</div>
</div>
Creator
  • 1,502
  • 4
  • 17
  • 30
0

Use display:flex style property like below.

body {
  margin:0;
}

.test {
  background: green;
  color:#fff;
  display:flex;
}

.test div {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #ccc;
  background-color: green;
  height: 50px;
}
<div class="test">
  <div>Left options</div>
  <div>Center div</div>
  <div>Username: test (string can change)</div>
</div>
Napoleon
  • 340
  • 3
  • 13
Pravin Vavadiya
  • 3,195
  • 1
  • 17
  • 34
0

float:left; to all divs within .test would do the trick.

.test>div{float:left;}

If you would like the divs to take up full width, then give it the width of width:33.3333%; (no. of divs / 100)

DEMO

Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
0

I am asuming that you want the div2 to keep it's size, and div1 and div3 elements to grow until they touch it. Set for those elements a flex-basis of 0:

body {
  margin: 0;
}
.test {
  background: green;
  color: #fff;
  display: flex;
}
.test .div2 {
  background: red;
}
.test .div1,
.test .div3 {
  flex-basis: 0;
  flex-grow: 1;
}
.div3 {
  text-align: right;
}
<div class="test">
  <div class="div1">Left options</div>
  <div class="div2">Center div</div>
  <div class="div3">Username: test (string can change)</div>
</div>
vals
  • 61,425
  • 11
  • 89
  • 138