下面列出了解决此问题的三种方法:
- 默认情况下
- 使用内联块属性
- 在width和height中使用fit-content属性
HTML div默认情况下适合其中的内容。该示例如下所示:
范例1:
<
!DOCTYPE html>
<
html lang = "en" dir = "ltr">
<
head>
<
meta charset = "utf-8">
<
title>
lsbin Example<
/title>
<
!--CSS Code-->
<
style media = "screen">
body {
background: orange;
overflow: hidden;
color: white;
}
.lsbin {
text-align: center;
background: dodgerblue;
position: absolute;
top: 50%;
left: 1%;
right: 1%;
}
<
/style>
<
/head>
<
body>
<
!-- HTML Code -->
<
h1 style = "color:forestgreen;
top:35%;
left: 35%;
position:absolute;
">
Geeks For Geeks
<
/h1>
<
div class = "lsbin">
Cascading Style Sheets, fondly referred
to as CSS, is a simply designed language
intended to simplify the process of
making web pages presentable. CSS allows
you to apply styles to web pages. More
importantly, CSS enables you to do this
independent of the HTML that makes up
each web page.
<
/div>
<
/body>
<
/html>
【如何使用CSS设置div宽度以适合内容()】输出如下:
文章图片
使用内联块属性:使用display:inline-block属性可根据其内容设置div大小。
范例2:
<
!DOCTYPE html>
<
html lang = "en">
<
head>
<
meta charset = "utf-8">
<
title>
lsbin Example<
/title>
<
!--CSS Code-->
<
style media = "screen">
body {
background: violet;
overflow: auto;
color: white;
}
.lsbin {
text-align: center;
background: dodgerblue;
position: absolute;
display: inline-block;
left: 1%;
right: 1%;
top: 50%;
}
<
/style>
<
/head>
<
body>
<
!-- HTML Code -->
<
h1 style="color: forestgreen;
top: 35%;
left: 35%;
position: absolute;
">
Geeks For Geeks
<
/h1>
<
div class = "lsbin">
Cascading Style Sheets, fondly referred
to as CSS, is a simply designed language
intended to simplify the process of
making web pages presentable. CSS allows
you to apply styles to web pages. More
importantly, CSS enables you to do this
independent of the HTML that makes up
each web page.
<
/div>
<
/body>
<
/html>
输出如下:
文章图片
在width和height中使用fit-content属性:
在此方法中, 我们将width和height属性设置为fit-content值。
范例3:
<
!DOCTYPE html>
<
html lang = "en" dir = "ltr">
<
head>
<
meta charset = "utf-8">
<
title>
Geeks for Geeks Example<
/title>
<
!--CSS Code-->
<
style media = "screen">
body {
background: tomato;
overflow: hidden;
color: white;
}
.lsbin {
background: crimson;
position: absolute;
width:fit-content;
height:fit-content;
left: 0;
top: 50%;
}
<
/style>
<
/head>
<
body>
<
!-- HTML Code -->
<
h1 style = "color: lime;
top: 35%;
left: 35%;
position: absolute;
">
Geeks For Geeks
<
/h1>
<
div class = "lsbin">
Cascading Style Sheets, fondly referred
to as CSS, is a simply designed language
intended to simplify the process of
making web pages presentable. CSS allows
you to apply styles to web pages. More
importantly, CSS enables you to do this
independent of the HTML that makes up
each web page.
<
/div>
<
/body>
<
/html>
输出如下:
文章图片
推荐阅读
- 三星研发中心面试问题
- Directi面试问题详细分享
- 算法设计(循环调度算法程序详细实现S1)
- DART和C++之间有什么区别()
- PHP如何使用date_isodate_set()函数(用法实例)
- 使用Java在原始数组中查找最大值或最小值
- Nodejs使用nodemon自动重启NodeJs服务器
- 给定以十进制为底的数字N,请以任意底数(底为b)查找其位数
- Go语言中的select语句怎么使用(用法示例解析)