EN
CSS - make div element to be not larger than its contents
1 answers
0 points
How can I make a div
element to be not larger than its contents?
I would like the .parent
element width be only as wide as the .child
element.
My code:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.parent {
7
background: orange;
8
}
9
10
.child {
11
height: 100px;
12
background: yellow;
13
}
14
15
</style>
16
</head>
17
<body>
18
<div class="parent">
19
<table class="child">
20
<tr>
21
<th>ID</th>
22
<th>Username</th>
23
</tr>
24
<tr>
25
<td>1</td>
26
<td>Mark</td>
27
</tr>
28
</table>
29
</div>
30
</body>
31
</html>
1 answer
0 points
This effect is called "shrinkwrapping" and there are couple of ways to achieve it (display: inline, float, min/max-width). All of the solutions have different side effects.
In your case, I would use display: inline-block
to make .parent
width equal to the .child
element.
Quick solution:
xxxxxxxxxx
1
.parent {
2
display: inline-block;
3
}
Practical example
In this section we present full working, runnable example of using display: inline-block
property in HTML5 web page template.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.parent {
7
background: orange;
8
display: inline-block; /* <----- required */
9
}
10
11
.child {
12
height: 100px;
13
background: yellow;
14
}
15
16
</style>
17
</head>
18
<body>
19
<div class="parent">
20
Parent element text...
21
<table class="child">
22
<tr>
23
<th>ID</th>
24
<th>Username</th>
25
</tr>
26
<tr>
27
<td>1</td>
28
<td>Mark</td>
29
</tr>
30
</table>
31
</div>
32
</body>
33
</html>
References
0 commentsShow commentsAdd comment