gpt4 book ai didi

html - parent 宽度自动和 child 固定宽度

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:39 24 4
gpt4 key购买 nike

我在父元素中居中固定宽度的子元素。当出现水平滚动时,例如在移动设备上,父级宽度变得小于子级,并且由于父级上有背景颜色,所以看起来很难看,我该如何解决?

.parent {
background: #555;
}

.child {
width: 1000px;
margin: 0 auto;
color: red;
font-size: 50px;
}
<body>
<div class="parent">
<div class="child">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea quas aut reiciendis quaerat, possimus, quidem veniam et sequi ullam labore obcaecati iure alias iusto atque explicabo facere, aperiam nobis quam.</div>
</div>
</body>

最佳答案

编辑:将 .parent 设为 inline-block 并设置为 min-width: 100% 使其增长以适应浏览器,但也不会缩小到小于其内容

.parent {
background: #555;
display: inline-block;
min-width: 100%;
}

.child {
width: 1000px;
color: red;
font-size: 50px;
}
<div class="parent">
<div class="child">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea quas aut reiciendis quaerat, possimus, quidem veniam et sequi ullam labore obcaecati iure alias iusto atque explicabo facere, aperiam nobis quam.</div>
</div>


基于您提供的代码的三个选项:

将宽度放在 .parent 元素上

.parent {
background: #555;
width: 1000px;
}

.child {
color: red;
font-size: 50px;
}
<div class="parent">
<div class="child">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea quas aut reiciendis quaerat, possimus, quidem veniam et sequi ullam labore obcaecati iure alias iusto atque explicabo facere, aperiam nobis quam.</div>
</div>

.parent 设为内联 block ,使其根据内容增长

.parent {
background: #555;
display: inline-block;
}

.child {
width: 1000px;
color: red;
font-size: 50px;
}
<div class="parent">
<div class="child">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea quas aut reiciendis quaerat, possimus, quidem veniam et sequi ullam labore obcaecati iure alias iusto atque explicabo facere, aperiam nobis quam.</div>
</div>

使 .parent 元素可滚动

.parent {
background: #555;
overflow: auto;
}

.child {
width: 1000px;
color: red;
font-size: 50px;
}
<div class="parent">
<div class="child">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea quas aut reiciendis quaerat, possimus, quidem veniam et sequi ullam labore obcaecati iure alias iusto atque explicabo facere, aperiam nobis quam.</div>
</div>

关于html - parent 宽度自动和 child 固定宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46266764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com