如何用CSS将文本容器居中置于页面底部且不超出body范围?
问题原因与解决方案
你之前用position: fixed导致底部文本超出body边界,是因为fixed定位是相对于浏览器视口的,完全脱离了body的文档流,所以body的margin和border无法约束它。要让底部文本被body包含并居中在底部,有两种靠谱的实现方式:
方案一:Flex布局(推荐)
把body设置为flex容器,通过布局属性让顶部标题和底部内容自然分布在容器两端,同时保证底部内容居中:
<body style="text-align: center; border: 5px solid black; margin: 50px; min-height: calc(100vh - 100px); display: flex; flex-direction: column; justify-content: space-between;"> <h1 style="text-transform: uppercase; font-size: 300%;">Book<br/> Title</h1> <p style="margin-bottom: 1em;"> <img alt="Logo" src="https://via.placeholder.com/150" style="height: 2.5em; width: auto;" /> <br/> Publisher's <br/> Name <br/> 2018 </p> </body>
min-height: calc(100vh - 100px):计算body的最小高度,100vh是视口高度,减去body上下margin的总和(50px×2),确保body能撑满视口且不超出页面。display: flex; flex-direction: column:让body内的子元素垂直排列。justify-content: space-between:自动把顶部标题推到容器顶端,底部文本推到容器底端。
方案二:绝对定位
给body设置相对定位作为参考容器,底部元素用绝对定位固定在body底部,同时给body预留底部空间避免内容被border遮挡:
<body style="text-align: center; border: 5px solid black; margin: 50px; position: relative; min-height: calc(100vh - 100px); padding-bottom: 4em;"> <h1 style="text-transform: uppercase; font-size: 300%;">Book<br/> Title</h1> <p style="position: absolute; bottom: 1em; left: 50%; transform: translateX(-50%);"> <img alt="Logo" src="https://via.placeholder.com/150" style="height: 2.5em; width: auto;" /> <br/> Publisher's <br/> Name <br/> 2018 </p> </body>
position: relative:将body设为绝对定位元素的参考父容器,让底部文本的定位相对于body而非视口。padding-bottom: 4em:给body底部留出足够空间,避免底部文本被border覆盖。bottom: 1em:让底部文本和body底部保持间距,不紧贴border。
内容的提问来源于stack exchange,提问作者user21879981
相关产品推荐
相关产品推荐

