How to change text (not font size) according to screen size in CSS?

对着背影说爱祢 提交于 2020-01-30 20:25:07

问题


I want to use abbreviation of days in small screen size.
For example when screen is shrinked I want to change 'Saturday' to 'Sat'.
How can I do this?


回答1:


Have 2 spans with full and short strings, then when below target resolution, swap between them using a media query:

HTML

<span class="full-text">Saturday</span>
<span class="short-text">Sat</span>

CSS

// Hide short text by default (resolution > 1200px)
.short-text { display: none; }

// When resolution <= 1200px, hide full text and show short text
@media (max-width: 1200px) {
    .short-text { display: inline-block; }
    .full-text { display: none; }
}

Replace 1200px with your target resolution breakpoint.

More on CSS media queries




回答2:


An example using ::after. Not sure if it's accessible to screen readers and such.

Press "full page" and resize to below 500px to see in action.

Benefits of this approach are:

  • All content is in the html file, not in css
  • I think that by only hiding the day label, and not removing its content, you circumvent some accessibility issues

@media screen and (max-width: 500px) {
    /* Add a pseudo element with the 
       text from attribute 'data-abbr' */
    .day[data-abbr]::after { 
        content: attr(data-abbr); 
    }
    
    /* Hide the original label */
    .day > span { display: none; }
}
<div class="day" data-abbr="sat">
    <span>Saturday</span>
</div>


<div class="day" data-abbr="sun">
    <span>Sunday</span>
</div>



回答3:


You can use Jquery for this

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
   if($( window ).width() < 767){
       $("p").text("Sat");
   }else{
       $("p").text("Saturday");
   }
});
$( window ).resize(function() {
	if($( window ).width() < 767){
       $("p").text("Sat");
   }else{
       $("p").text("Saturday");
   }
});
</script>
</head>
<body>
<p>Saturday</p>
</body>
</html>

Here I have placed two functions .ready() and .resize, I have used resize function for just testing, use anyone or both it as per your need.



来源:https://stackoverflow.com/questions/39894291/how-to-change-text-not-font-size-according-to-screen-size-in-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!