简体   繁体   English

CSS:将子div宽度自动设置为内容,而不是完整的父宽度

[英]CSS: Make child div width auto to content in it, not the full parent width

I'm having some problems with my css. 我的css有些问题。 Sorry about the title, i'm not too sure how to explain it in a few words, but here it is. 对标题感到抱歉,我不太清楚如何用几句话来解释它,但现在就是这样。 This is the problem i'm having. 这是我遇到的问题。 I have a wrapper parent div, and that is aligned to the center of the page. 我有一个包装父div,它与页面的中心对齐。 Inside that div I have another div, and that div contains pictures in it. 在那个div里面我有另一个div,那个div里面有图片。 The problem is I have the child div set to width:auto, and the width is always the full length of the parent div. 问题是我将子div设置为width:auto,宽度始终是父div的全长。 What I want is it to auto scale to be just as big as the content inside it, so I can center it within the parent div. 我想要的是自动缩放与其中的内容一样大,所以我可以将它放在父div中。 Here is a picture of what I mean. 这是我的意思的图片。

enter image description here 在此输入图像描述

The grey part is my parent div, wrapper, and the red part is my child div, gameswrapper. 灰色部分是我的父div,包装器,红色部分是我的孩子div,gameswrapper。 I want gameswrapper to be the same size as the game pictures in it 我希望gameswrapper与其中的游戏图片大小相同

Here is my css 这是我的CSS

#wrapper {
background: #ddd;
width: 70%;
max-width: 70%;
margin: auto;
padding: 10px;
font-family: 'CaviarDreamsBold';
}
#gamesdisplay {
    display:block;
}
#searchdisplay {
    display:block;
}
.artwork {
margin: 6px;
width: 150px;
height: 230px;  
background: #666;
display: inline-block;
cursor: pointer;
}

And this is my html 这是我的HTML

<div id="wrapper">
<div id="gamesdisplay" style="overflow:auto; width:auto; background:red;">
<a href=''><div class="artwork" style="background: url('')"></div></a>

Anyone know how to solve this? 有谁知道如何解决这个问题?

I would do something like this: 我会做这样的事情:

https://jsbin.com/tohuluzehu/edit?html,css,output https://jsbin.com/tohuluzehu/edit?html,css,output

Simply use inline-block as the display mode of the child... this will take the width expanding behaviour of the div away :) 只需使用内联块作为孩子的显示模式...这将取得div的宽度扩展行为:)

you can do this by setting #wrapper to have text-align: center and giving #gamesdisplay the dipslay type of inline-block . 您可以通过将#wrapper设置为text-align: center并将#gamesdisplay设置为inline-block的dipslay类型来#gamesdisplay此目的。

Here's the CSS (inc your original CSS): 这是CSS(包括您的原始CSS):

#wrapper {
  background: #ddd;
  width: 70%;
  max-width: 70%;
  margin: auto;
  padding: 10px;
  font-family: 'CaviarDreamsBold';
  text-align: center;
}
#gamesdisplay {
  display: inline-block;
  padding: 10px;
}
#searchdisplay {
  display:block;
}

and here's a working example on codepen: 这是一个关于codepen的工作示例:

http://codepen.io/sonnyprince/pen/grvmzj http://codepen.io/sonnyprince/pen/grvmzj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM