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
  • 307,417
  • 93
  • 525
  • 644
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
  • 7,507
  • 3
  • 52
  • 78
Jagajit Prusty
  • 2,000
  • 1
  • 15
  • 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,492
  • 4
  • 17
  • 29
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
  • 338
  • 3
  • 13
Pravin Vavadiya
  • 3,099
  • 1
  • 15
  • 33
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

Rusty
  • 7,918
  • 10
  • 50
  • 72
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
  • 58,159
  • 11
  • 81
  • 129