Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS "width: auto" is not working on <div>

Tags:

html

css

I want .test_info be width auto, not the same as the width of #test.

https://jsfiddle.net/ef6ukobf/

#test {
  background: #26A65B;
  height: 30px;
  width: auto;
  margin-top: -8px;
  margin-left: -8px;
  margin-right: -8px;
}
.test_info {
  background: #00ff00;
  border-radius: 5px;
  height: 20px;
  width: auto;
  margin-top: -2px;
  margin-left: 20px;
}
<div id="test">
  <div class="test_info">50</div>
</div>
like image 482
Deimis Avatar asked Jul 07 '16 17:07

Deimis


People also ask

How do I make a div auto adjust width?

Using width, max-width and margin: auto; Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins: This <div> element has a width of 500px, and margin set to auto.

Why is auto not working in CSS?

The most common reason that the margin: auto; is not working might be that you have not set the width of the element. If you haven't set the width of the element and try applying margin: auto; , it will not work.

How do I force a div to full width?

The width property is used to fill a div remaining horizontal space using CSS. By setting the width to 100% it takes the whole width available of its parent. Example 1: This example use width property to fill the horizontal space. It set width to 100% to fill it completely.

Why my div is not responsive?

Because your div has a fixed width, it's not going to be responsive because the container size never changes.


1 Answers

The <div> element is block level, by default it takes the entire available width of the container.

If you want it to be auto width (depends on the content inside), you can do:

.test_info {
  display: inline-block; /*or table*/
}

#test {
  background: #26A65B;
}
.test_info {
  background: #00ff00;
  display: inline-block;
}
<div id="test">
  <div class="test_info">50</div>
</div>
like image 181
Stickers Avatar answered Sep 21 '22 11:09

Stickers