英文:
Flex size adapt to child div
问题
我正在使用TailwindCSS来创建我的CSS,并试图弄清楚如何利用flexbox类来使父级div的宽度与子div相同,以便可以将图像和标题居中,而不是居中在页面的中心。我是否需要设置一个空的div来利用这个div右侧的空间,还是需要一个适当执行此操作的flexbox样式?
代码:
<div className="flex flex-col p-5">
<a
onClick={() => {
mediaPlayerState(true);
setNum(randomYTVideoGenerator(1, 5));
console.log(num);
}}
>
<Image
className="pb-1 items-center"
src="/windows-media-player.png"
width={50}
height={50}
></Image>
<div className="text-white font-semibold">媒体播放器</div>
</a>
</div>
<details>
<summary>英文:</summary>
I am using TailwindCSS to create my css and trying to figure out how to utilize the flexbox classes to make the parent div be the size of width of my child divs so I can center the image and title without it centering to the center of the page. Would I need to set up an empty div that utilizes the space to the right of this div or a flexbox style that takes this action appropriately?
**Code:**
<div className="flex flex-col p-5">
<a
onClick={() => {
mediaPlayerState(true);
setNum(randomYTVideoGenerator(1, 5));
console.log(num);
}}
>
<Image
className="pb-1 items-center"
src="/windows-media-player.png"
width={50}
height={50}
></Image>
<div className="text-white font-semibold">Media Player</div>
</a>
</div>
[![div][1]][1]
[1]: https://i.stack.imgur.com/dqhW6.png
</details>
# 答案1
**得分**: 0
考虑以下两种方式之一:
- 通过 `w-max` 类将 `width: max-content` 应用于 `<div>` 元素。
- 通过 `inline-flex` 类将 `display: inline-flex` 应用于 `<div>` 元素。
```html
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-html -->
<script src="https://cdn.tailwindcss.com"></script>
<body class="bg-slate-950">
<div class="flex flex-col p-5 w-max">
<a>
<img
class="pb-1 items-center"
src="https://picsum.photos/50/50"
width={50}
height={50}
/>
<div class="text-white font-semibold">Media Player</div>
</a>
</div>
<div class="inline-flex flex-col p-5">
<a>
<img
class="pb-1 items-center"
src="https://picsum.photos/50/50"
width={50}
height={50}
/>
<div class="text-white font-semibold">Media Player</div>
</a>
</div>
<!-- end snippet -->
英文:
Consider either:
- Applying
width: max-content
to the<div>
via thew-max
class. - Applying
display: inline-flex
instead ofdisplay: flex
to the<div>
via theinline-flex
class.
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-html -->
<script src="https://cdn.tailwindcss.com"></script>
<body class="bg-slate-950">
<div class="flex flex-col p-5 w-max">
<a>
<img
class="pb-1 items-center"
src="https://picsum.photos/50/50"
width={50}
height={50}
/>
<div class="text-white font-semibold">Media Player</div>
</a>
</div>
<div class="inline-flex flex-col p-5">
<a>
<img
class="pb-1 items-center"
src="https://picsum.photos/50/50"
width={50}
height={50}
/>
<div class="text-white font-semibold">Media Player</div>
</a>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论