1

I have two divs with width: 50% and text content inside that are wrapped in the container. The problem is that when text content changes, width also changes:

text1

text2

I have a fixed width of the container equal to 200px:

.container {
  display: block;
  width: 200px;
}

.text1 {
  background-color: red;
  width: 50%;
  display: inline;
}

.text2 {
  background-color: blue;
  width: 50%;
  display: inline;
}
<div class='container'>
  <div class='text1'>Text1</div>
  <div class='text2'>Text2</div>
</div>

How I can keep 50% of child div width even when text is changing? Link to JSFiddle:

Nitheesh
  • 19,238
  • 3
  • 22
  • 49
Karen
  • 1,249
  • 4
  • 23
  • 46

3 Answers3

5

You may use CSS Flexbox here:

.container {
  display: flex;
  width: 200px;
}

.text1 {
  background-color: red;
  width: 50%;
}

.text2 {
  background-color: blue;
  width: 50%;
}
<div class='container'>
  <div class='text1'>Text1</div>
  <div class='text2'>Text2</div>
</div>
voiarn
  • 547
  • 6
  • 13
1

CSS Solution

inline elements only consume the the width that its content specifies.

Go for display: block; with float: left; or display: flex implementation.

display: block implementation

.container {
  display: block;
  width: 200px;
}

.text {
  width: 50%;
  display: block;
  float: left;
}

.text1 {
  background-color: red;
}

.text2 {
  background-color: blue;
}
<div class='container'>
  <div class='text text1'>1</div>
  <div class='text text2'>Text2</div>
</div>

display: flex implementation

In case of flex layout, there is no need to specify width to the child elements. Just add flex-grow: 1 or flex: 1 to the child elements.

.container {
  display: flex;
  width: 200px;
}

.text {
  flex: 1;
}

.text1 {
  background-color: red;
}

.text2 {
  background-color: blue;
}
<div class='container'>
  <div class='text text1'>1</div>
  <div class='text text2'>Text2</div>
</div>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
0

Although flexbox should work, as given by other responses, you can also do it by using columns.

Just specify column-count to 2 columns on .container and set column-width to 50% on .text1 and .text2.

Here´s it:

.container {
  display: block;
  width: 200px;
  column-count: 2;
}

.text1 {
  background-color: red;
  column-width: 50%;
}

.text2 {
  background-color: blue;
  column-width: 50%;
}

<div class='container'>
     <div class='text1'>1</div>
     <div class='text2'>Text2</div>
</div>

Here´s the JSFiddle.