如何让DIV宽度适配内部文本并实现多文本页面居中
How to Make Multiple Text Blocks Side-by-Side and Centered with Auto-Width Container
Hey there! Let's break down how to fix your layout issue. The key goals here are: getting your paragraphs to sit side-by-side, making the container automatically fit its content, and centering the whole thing on the page.
First, let's address the small issues in your current CSS:
padding-left: autoandpadding-right: autodon't work — padding values can't be set toauto, so those lines aren't doing anything for you.- While
display: inline-blockon your container is a solid start, we need to tweak how the container is centered and how the paragraphs inside are arranged.
Solution 1: Flexbox (Modern & Recommended)
Flexbox makes this layout intuitive and clean. Here's the adjusted CSS:
/* Parent container: auto-fits content and centers itself */ .navigation-container { width: fit-content; /* Automatically sizes to match inner content */ margin: 0 auto; /* Centers the container horizontally in its parent */ display: flex; /* Arranges child paragraphs side-by-side */ gap: 1.5rem; /* Adds consistent space between paragraphs (adjust as needed) */ } /* Paragraphs: keeps text centered inside each block */ p { font-family: 'Roboto', serif; font-size: 1.5vh; text-align: center; margin: 0; /* Removes default paragraph margins to avoid unexpected spacing */ /* Add padding here if you need internal spacing, e.g., padding: 0.5rem; */ }
Solution 2: Inline-Block (Legacy-Friendly)
If you need to support older browsers, inline-block is a reliable alternative:
/* Parent container: auto-fits content */ .navigation-container { display: inline-block; /* Shrinks to fit its children */ margin: 0 auto; /* Centers the container */ /* If this doesn't center, add `text-align: center;` to the parent of .navigation-container (like <body>) */ } /* Paragraphs: sit side-by-side and keep text centered */ p { font-family: 'Roboto', serif; font-size: 1.5vh; text-align: center; display: inline-block; /* Makes paragraphs line up horizontally */ margin: 0 1rem; /* Adds horizontal space between paragraphs */ /* Add padding here for internal spacing */ }
Quick Tips:
- For the inline-block solution, if your container still won't center, double-check that its parent element has
text-align: center;applied. - Use
gap(for flex) ormargin(for inline-block) to control spacing between paragraphs so they don't look cramped.
内容的提问来源于stack exchange,提问作者user9642283
相关产品推荐
相关产品推荐

