CSS 將文章中圖片自動居中
對於一個運營超過500+站點的我來說.作為文章的圖片居中是不可避免的事情,每次都會需要對應的調整,十年前記錄,今天還得記錄,詳細一下有多重要.
早些年是利用在圖片的標籤內寫居中,現在都是css自適應居中.這裡是最佳的辦法.畢竟對於數據多的人來說,幾個代碼可以改變全局,還不影響搜索降權.
何樂而不為…🙄
margin: 0px auto;
display: block;
大家也不要小看這個代碼, 定義塊級元素,自適應居中,如果你的圖片超過樣式框,可添加 max-width: 700px;來定義.
這中相對值可以在移動端也有很好的展示.
/* 通用樣式,確保所有圖片都能受到影響 */
img {
max-width: 100%; /* 圖片最大寬度為其容器的100% */
height: auto; /* 圖片高度自動調整,保持寬高比 */
display: block; /* 使圖片成為塊級元素,以便居中對齊 */
margin: 0 auto; /* 使用margin:auto將圖片水平居中 */
}
/* 針對移動端的媒體查詢 */
@media only screen and (max-width: 767px) {
img {
max-width: 100%; /* 保持圖片在移動端的響應性 */
}
}
早期的文本居中方法
.container { text-align: center; }
.container img { display: inline-block; }
相對定位法:
.container { position: relative; }
.container img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
Flexbox法:
.container { display: flex; justify-content: center; align-items: center; }
Grid布局法:
.container {
display: grid;
place-items: center;
}
margin: auto法:
.container {
margin-left: auto;
margin-right: auto;
}
當然,所有的方法都是解決問題,首推我前面的方法,其他的方法更多的只為參考記錄.😀
原創文章,作者:超哥,如若轉載,請註明出處:https://www.chaoneo.cn/zh-hant/archives/3534.html
如果您覺得超哥分享對您有所幫助的話,記得打賞給我😀